Skip to content

Instantly share code, notes, and snippets.

@AdamBrouwersHarries
Created September 10, 2015 14:44
Show Gist options
  • Save AdamBrouwersHarries/4857ecb7d47ea1c69f74 to your computer and use it in GitHub Desktop.
Save AdamBrouwersHarries/4857ecb7d47ea1c69f74 to your computer and use it in GitHub Desktop.
Super simple arithmetic expressions in haskell
{-# LANGUAGE GADTs #-}
module Main where
data Expr a where
N :: Float -> Expr Float
(:+) :: Expr Float -> Expr Float -> Expr Float
(:*) :: Expr Float -> Expr Float -> Expr Float
(:-) :: Expr Float -> Expr Float -> Expr Float
(:/) :: Expr Float -> Expr Float -> Expr Float
App :: (Float -> Float) -> Expr Float -> Expr Float
instance Show (Expr a) where
show (N i) = show i
show (i :+ j) = "("++show i ++ "+" ++ show j++")"
show (i :- j) = "("++show i ++ "-" ++ show j++")"
show (i :* j) = "("++show i ++ "*" ++ show j++")"
show (i :/ j) = "("++show i ++ "/" ++ show j++")"
show (App _ x) = "f(" ++ show x ++ ")"
eval :: Expr a -> a
eval (N i) = i
eval (i :+ j) = eval i + eval j
eval (i :- j) = eval i - eval j
eval (i :* j) = eval i * eval j
eval (i :/ j) = eval i / eval j
eval (App f x) = f (eval x)
comp :: Expr Float
comp = ((N 10 :+ N 12) :* N 10) :- N 15
comp2 :: Expr Float
comp2 = App (\x -> x*x) (((N 10 :+ N 12) :* N 10) :- N 15)
comp3 :: Expr Float
comp3 = (N 10 :* N 10) :/ N 3
computations :: [Expr Float]
computations = [comp, comp2, comp3]
main :: IO ()
main = mapM_ (\expr -> print (show expr ++ " = " ++ show (eval expr)))
computations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment