Quadratic equation in Haskell
Example for versions
GHC 6.10.4
Haskell provides complex datatype. Function quadratic
accepts a list of complex numbers and returns a list of equation roots. Notation root sign
allows to generalize the notation of roots for two signs of square root.
module Main where
import Data.Complex
import System.IO (hFlush, stdout)
quadratic :: (Complex Double, Complex Double, Complex Double) -> [Complex Double]
quadratic (0, _, _) = []
quadratic (a, b, c)
| d == 0 = [root (+)]
| otherwise = [root (+), root (-)]
where d = b*b - 4*a*c
root sign = sign (-b) (sqrt d) / (2*a)
main = do
putStr "A = "
hFlush stdout
a <- readLn :: IO Double
putStr "B = "
hFlush stdout
b <- readLn :: IO Double
putStr "C = "
hFlush stdout
c <- readLn :: IO Double
print $ quadratic (realToFrac a, realToFrac b, realToFrac c)
Comments
]]>blog comments powered by Disqus
]]>