Created
September 28, 2019 12:09
-
-
Save haruo-wakakusa/6867e2ca02db40d004cc9ad274c1b32a to your computer and use it in GitHub Desktop.
2次方程式の解を求めるプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 2次方程式の解を求めるプログラム | |
import Control.Monad | |
data Equation = | |
Equation { a :: Double, b :: Double, c :: Double } deriving Show | |
data Solution = ZeroSols | OneSol Double | TwoSols Double Double deriving Show | |
discriminant :: Equation -> Double | |
discriminant Equation { a = a, b = b, c = c } = b * b - 4.0 * a * c | |
solve :: Equation -> Solution | |
solve eq = slv eq $ discriminant eq | |
slv :: Equation -> Double -> Solution | |
slv Equation { a = a, b = b, c = c } d | |
| d > 0.0 = | |
TwoSols | |
((- b - (sqrt d)) / 2.0 / a) | |
((- b + (sqrt d)) / 2.0 / a) | |
| d == 0.0 = OneSol (- b / 2.0 / a) | |
| otherwise = ZeroSols | |
main = do | |
forM_ | |
[ | |
Equation { a = 1.0, b = -2.0, c = 1.0 }, | |
Equation { a = 1.0, b = 2.0, c = 1.0 }, | |
Equation { a = 3.0, b = 2.0, c = -1.0 }, | |
Equation { a = 9.0, b = -12.0, c = 4.0 }, | |
Equation { a = 1.0, b = 2.0, c = 3.0 } | |
] | |
(\x -> do print $ solve x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment