-- ---------------------------------------- -- -- Simple expression evaluator -- for integer arithmetic -- -- ---------------------------------------- module Expr0 where import Data.Maybe -- ---------------------------------------- -- syntactic domains data Expr = Const Int | Binary BinOp Expr Expr deriving (Show) data BinOp = Add | Sub | Mul | Div | Mod deriving (Eq, Show) -- ---------------------------------------- -- semantic domains type Result = Int -- ---------------------------------------- -- the meaning of an expression eval :: Expr -> Result eval (Const i) = i eval (Binary op l r) = let mf = lookupMft op in mf (eval l) (eval r) -- ---------------------------------------- -- the meaning of binary operators type MF = Result -> Result -> Result lookupMft :: BinOp -> MF lookupMft op = case lookup op mft of Nothing -> error "operation not implemented" Just mf -> mf mft :: [(BinOp, MF)] mft = [ (Add, (+)) , (Sub, (-)) , (Mul, (*)) , (Div, div) ] -- ---------------------------------------- -- sample expressions e1 = Binary Mul (Binary Add (Const 2) (Const 4) ) (Const 7) e2 = Binary Div (Const 1) (Const 0) e3 = Binary Mod (Const 1) (Const 0) [v1,v2,v3] = map eval [e1, e2, e3] -- ----------------------------------------