Wednesday, September 8, 2010

AST, Logic Formulas, and Haskell

While sitting in a tutorial today, I began translating the example given to Haskell, a language I have little experience with.


data Logic = Tru | Fls | And Logic Logic |
  Or Logic Logic | Implies Logic Logic | Not Logic
  deriving Show
eval_logic :: Logic -> Bool
eval_logic l = case l of
  Tru -> True
  Fls -> False
  And x y -> eval_logic x && eval_logic y
  Or x y -> eval_logic x || eval_logic y
  Implies x y -> eval_logic (Or (Not x) y)
  Not x -> not (eval_logic x)
logic_formula = (And Tru (Or Tru Fls))
main =
  putStrLn (show logic_formula) >>
  putStrLn (show (eval_logic logic_formula))


The example builds up an AST, here for a small logic language, and then also evaluates it uses pattern matching on the algebraic data type and recursion. (btw, the name Tru and Fls are used because True and False are already values in Haskell)

For those of you just getting started using Haskell to create little languages and DSLs, hopefully this will be a helpful snippet to start off.

No comments:

Post a Comment