Polynomial derivative: Difference between revisions

→‎{{header|Haskell}}: added solution
(→‎{{header|Haskell}}: added solution)
Line 173:
Differentiates to
1 - 3x^2- 4x^3</pre>
 
=={{header|Haskell}}==
 
<lang haskell>deriv = zipWith (*) [1..] . tail
 
main = mapM_ (putStrLn . line) ps
where
line p = "\np = " ++ show p ++ "\np' = " ++ show (deriv p)
ps = [[5],[4,-3],[-1,6,5],[-4,3,-2,1],[1,1,0,-1,-1]]</lang>
 
<pre>main
 
p = [5]
p' = []
 
p = [4,-3]
p' = [-3]
 
p = [-1,6,5]
p' = [6,10]
 
p = [-4,3,-2,1]
p' = [3,-4,3]
 
p = [1,1,0,-1,-1]
p' = [1,0,-3,-4]</pre>
 
With fancy output
 
<lang haskell>{-# language LambdaCase #-}
 
showPoly [] = "0"
showPoly p = foldl1 term $ dropWhile null $ foldMap showMono $ zip [0..] p
where
showMono = pure . \case (_,0) -> ""
(0,c) -> show c
(1,c) -> show c ++ "*x"
(i,1) -> "x^" ++ show i
(i,c) -> show c ++ "*x^" ++ show i
term r = \case [] -> r
'-':t -> r ++ " - " ++ t
t -> r ++ " + " ++ t
 
main = mapM_ (putStrLn . line) ps
where
line p = "\np = " ++ showPoly p ++ "\np' = " ++ showPoly (deriv p)
ps = [[5],[4,-3],[-1,6,5],[-4,3,-2,1],[1,1,0,-1,-1]]</lang>
 
<pre> main
 
p = 5
p' = 0
 
p = 4 - 3*x
p' = -3
 
p = -1 + 6*x + 5*x^2
p' = 6 + 10*x
 
p = -4 + 3*x - 2*x^2 + x^3
p' = 3 - 4*x + 3*x^2
 
p = 1 + 1*x - 1*x^3 - 1*x^4
p' = 1 - 3*x^2 - 4*x^</pre>
 
=={{header|jq}}==
Anonymous user