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)

 

 

Posted by Scripter
,