Skip to content

Instantly share code, notes, and snippets.

@nebuta
Created July 27, 2013 21:17
Show Gist options
  • Save nebuta/6096315 to your computer and use it in GitHub Desktop.
Save nebuta/6096315 to your computer and use it in GitHub Desktop.
Haskell AST basic example
data Exp r = Const r | Add (Exp r) (Exp r) | Subtract (Exp r) (Exp r)
eval :: (Num r) => Exp r -> r
eval (Const v) = v
eval (Add e1 e2) = (eval e1) + (eval e2)
eval (Subtract e1 e2) = (eval e1) - (eval e2)
reify :: (Show r) => Exp r -> String
reify (Const v) = show v
reify (Add e1 e2) = concat ["(",reify e1,"+",reify e2,")"]
reify (Subtract e1 e2) = concat ["(",reify e1,"-",reify e2,")"]
main :: IO ()
main = do
putStrLn $ reify exp1
putStrLn $ reify exp2
exp1 = Subtract (Add (Const 3) (Const 2)) (Const 1)
exp2 = Subtract (Add (Const (3::Double)) (Const 2)) (Const 1)
{-
Result on GHCi:
*Main> main
((3+2)-1)
((3.0+2.0)-1.0)
*Main> :t exp1
exp1 :: Exp Integer
*Main> :t exp2
exp2 :: Exp Double
*Main> :t (Const 1)
(Const 1) :: Num r => Exp r
*Main> :t (Const "hello")
(Const "hello") :: Exp [Char]
*Main> eval (Const "hello")
<interactive>:108:1:
No instance for (Num [Char]) arising from a use of `eval'
Possible fix: add an instance declaration for (Num [Char])
In the expression: eval (Const "hello")
In an equation for `it': it = eval (Const "hello")
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment