data Logic = Tru | Fls | And Logic Logic |Or Logic Logic | Implies Logic Logic | Not Logicderiving Showeval_logic :: Logic -> Booleval_logic l = case l ofTru -> TrueFls -> FalseAnd x y -> eval_logic x && eval_logic yOr x y -> eval_logic x || eval_logic yImplies 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