Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Calculator

Name: smott 2005-07-09 11:44

{-
Man, this board is slow. Here, have a calculator.
very minimalist, but i think it can do most things.
of course it's horribly verbose, but writing a real
parser = pain. the code is very simple and elegant
imo
-}

module Main
    where

import System.Environment (getArgs)
import Control.Monad        (liftM)

data Exp = Add Exp Exp | Mul Exp Exp
         | Sin Exp     | Neg Exp
         | Num Float   | Inv Exp
    deriving (Show, Read, Eq)

eval :: Exp -> Float
eval (Add e1 e2) = eval e1  +   eval e2
eval (Mul e1 e2) = eval e1  *   eval e2
eval (Sin    e1) = sin      $   eval e1
eval (Neg    e1) = negate   $   eval e1
eval (Inv    e1) = 1        /   eval e1
eval (Num     n) = n

main :: IO ()
main = liftM unwords getArgs
       >>= print . eval . read


{-
# works like this:
$ ghc --make qcalc.hs -o qcalc
Chasing modules from: qcalc.hs
Compiling Main             ( qcalc.hs, qcalc.o )
Linking ...
$ ./qcalc "Sin (Add (Inv (Num 3.0)) (Neg (Num 2.0)))"
-0.99540794
-}

Name: Anonymous 2005-07-11 8:35

MORE LIKE f+=3 AM I RITE

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List