1 {-# LANGUAGE TypeSynonymInstances #-}
2 {-# LANGUAGE FlexibleInstances #-}
3 {-# OPTIONS_GHC -Wall #-}
8 import qualified ExprT as E
11 import qualified Data.Map as M
15 eval :: E.ExprT -> Integer
17 eval (E.Add e1 e2) = eval e1 + eval e2
18 eval (E.Mul e1 e2) = eval e1 * eval e2
21 evalStr :: String -> Maybe Integer
22 -- evalStr s = case (parseExp Lit Add Mul s) of
23 -- Just e -> Just (eval e)
25 evalStr s = fmap eval (parseExp E.Lit E.Add E.Mul s)
32 instance Expr E.ExprT where
37 reify :: E.ExprT -> E.ExprT
40 instance Expr Integer where
45 instance Expr Bool where
46 lit x | x <= 0 = False
51 newtype MinMax = MinMax Integer deriving (Show, Eq)
53 instance Expr MinMax where
55 add (MinMax x) (MinMax y) = MinMax (max x y)
56 mul (MinMax x) (MinMax y) = MinMax (min x y)
58 newtype Mod7 = Mod7 Integer deriving (Show, Eq)
60 instance Expr Mod7 where
61 lit x = Mod7 (x `mod` 7)
62 add (Mod7 x) (Mod7 y) = Mod7 ((x+y) `mod` 7)
63 mul (Mod7 x) (Mod7 y) = Mod7 ((x*y) `mod` 7)
66 instance Expr Program where
68 add x y = x ++ y ++ [Add]
69 mul x y = x ++ y ++ [Mul]
71 compile :: String -> Maybe Program
72 compile = parseExp lit add mul
75 data VarExprT = VarLit Integer
76 | VarAdd VarExprT VarExprT
77 | VarMul VarExprT VarExprT
84 instance Expr VarExprT where
89 instance HasVars VarExprT where
92 instance HasVars (M.Map String Integer -> Maybe Integer) where
95 instance Expr (M.Map String Integer -> Maybe Integer) where
97 add x y = \m -> case (x m) of
98 Just xv -> case (y m) of
99 Just yv -> Just (xv + yv)
102 mul x y = \m -> case (x m) of
103 Just xv -> case (y m) of
104 Just yv -> Just (xv * yv)
108 withVars :: [(String, Integer)]
109 -> (M.Map String Integer -> Maybe Integer)
111 withVars vs exp = exp $ M.fromList vs