I have written Haskell code to my spec to help me grasp types and syntax, because I am learning.
I hope to generalize it further to accommodate more kinds of equations. I am (perhaps prematurely) worried that repeated usage of delta
in multiple places is going to slow down my code, but I don't see how I can avoid it.
I am a bit confused about whether I should use Floating
class or just use Float
concrete type everywhere.
I appreciate any and all tips.
Here's the expected output
Equation -10.0x^2 +4.0x +1.0 = 0 has following 2 solutions:
0.28708285
-8.708288e-2
And the code
-- MathPrimer
delta :: Floating a => a -> a -> a -> a
x1 :: Floating a => a -> a -> a -> a
x2 :: Floating a => a -> a -> a -> a
delta a b c = b * b - 4 * a * c
x1 a b c = ( - b - sqrt(delta a b c)) / ( 4 * a * c )
x2 a b c = ( - b + sqrt(delta a b c)) / ( 4 * a * c )
class Algebraic equ where
algebraicForm :: equ -> String
class (ZeroEquation equ) where
solve :: equ -> [Float]
solutionCount :: equ -> Int
data Equation = Quadratic {a :: Float, b :: Float, c :: Float}
deriving (Show, Read, Eq)
instance (ZeroEquation Equation) where
solve (Quadratic a b c) = solutions
where
both = [x1 a b c, x2 a b c]
one = [x1 a b c]
zero = []
solutions = if _delta < 0 then zero else if _delta == 0 then one else both
_delta = (delta a b c)
solutionCount (Quadratic a b c) = count
where
count = if _delta < 0 then 0 else if _delta == 0 then 1 else 2
_delta = (delta a b c)
instance (Algebraic Equation) where
algebraicForm (Quadratic a b c) = show a ++ "x^2 +" ++ show b ++ "x +" ++ show c
showEquation :: Equation -> String
showEquation equ = "Equation " ++ description ++ " = 0 has following " ++ count ++ " solutions:\n" ++ solutions
where
count = show $ solutionCount equ
description = algebraicForm equ
solutions = unlines $ map show $ solve equ
main = do
let equation = Quadratic (-10) 4 1
putStrLn $ showEquation equation
sqrt
for a complex one to get complex. But I decided against it because it was no fun when there's only 2 or 0 solutions. I also would have to adjustFloat
andFloating
to some complex types I don't know yet. \$\endgroup\$ – loa_in_ Jan 12 at 21:59