GHC 의 runhaskell 명령으로 소스 파일을 직접 실행해도 되고,
ghc 명령으로 컴파일하여 생성된 실행파일을 실행해도 된다.
-- Filename: solveQuadratic.hs
-- Solve a quadratic equation.
--
-- Compile: ghc solveQuadratic.hs
-- Execute: solveQuadratic 1 3 2
--
-- Or
--
-- Execute: runhaskell solveQuadratic.hs 1 3 2
{-
Compile: ghc solveQuadratic.hs
Execute & Result: solveQuadratic 1 0 4
Quadratic Equation: 1.0x^2 + 0.0x + 4.0 = 0
Discriminant D = -16.0
x1 = 2.0j
x2 = -2.0j
Or
Execute & Result: runhaskell solveQuadratic.hs 1 0 4
Quadratic Equation: 1.0x^2 + 0.0x + 4.0 = 0
Discriminant D = -16.0
x1 = 2.0j
x2 = -2.0j
-}
module Main where
import System.Environment
import Data.Complex
import Text.Printf
printUsing :: IO ()
printUsing = do
putStrLn "Using: runhugs solveQuadratic.hs coeff2 coeff1 coeff0"
putStrLn "Or solveQuadratic coeff2 coeff1 coeff0"
putStrLn "Find the roots pf a quadratic equations."
printSolution :: [Char] -> Double -> Double -> IO()
printSolution msg x y = do
if not (y == 0) && not (x == 0)
then
printf "%s%f + %fj\n" msg x y
else if not (y == 0) && (x == 0)
then
printf "%s%fj\n" msg y
else
printf "%s%f\n" msg x
printEquation :: Double -> Double -> Double -> IO()
printEquation a b c = printf "Quadratic Equation: %fx^2 + %fx + %f = 0\n" a b c
solveEquation :: (RealFloat a) => a -> a -> a -> [Complex a]
solveEquation a b c = x1:x2:[] where
za = (a :+ 0)
zb = (b :+ 0)
zc = (c :+ 0)
discr = zb*zb - 4*za*zc
x1 = (-zb + sqrt (discr))/(2*za)
x2 = (-zb - sqrt (discr))/(2*za)
main :: IO ()
main = do
args <- getArgs
if not ((length args) == 3)
then printUsing
else do
let a1:b1:c1:ts = args
let a = read a1 :: Double
let b = read b1 :: Double
let c = read c1 :: Double
let d = b*b - 4.0*a*c
printEquation a b c
printf "Discriminant D = %g\n" d
let sols = solveEquation a b c
let x1:x2:x3 = sols
printSolution "x1 = " (realPart x1) (imagPart x1)
printSolution "x2 = " (realPart x2) (imagPart x2)
'프로그래밍 > Haskell' 카테고리의 다른 글
Haskell 언어로 행렬 곱셈하는 예제 (0) | 2012.05.28 |
---|---|
Haskell 언어로 복소수 계산과 분수 계산 쉽게 하기 (0) | 2012.05.27 |
30000! 빨리 계산하기 with Haskell (0) | 2010.07.20 |
숫자 맞추기 게임 with Haskell (0) | 2009.10.29 |
Haskell 언에에서 형(type) 변환하기 (0) | 2009.10.19 |