Skip to content

Instantly share code, notes, and snippets.

@haruo-wakakusa
Created September 28, 2019 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haruo-wakakusa/6867e2ca02db40d004cc9ad274c1b32a to your computer and use it in GitHub Desktop.
Save haruo-wakakusa/6867e2ca02db40d004cc9ad274c1b32a to your computer and use it in GitHub Desktop.
2次方程式の解を求めるプログラム
-- 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