import qualified ExprT as E
import Parser
import StackVM
-
+import qualified Data.Map as M
-- exercise 1
compile :: String -> Maybe Program
compile = parseExp lit add mul
+
+-- exercise 6
+data VarExprT = VarLit Integer
+ | VarAdd VarExprT VarExprT
+ | VarMul VarExprT VarExprT
+ | Var String
+ deriving (Show, Eq)
+
+class HasVars a where
+ var :: String -> a
+
+instance Expr VarExprT where
+ lit = VarLit
+ add = VarAdd
+ mul = VarMul
+
+instance HasVars VarExprT where
+ var = Var
+
+instance HasVars (M.Map String Integer -> Maybe Integer) where
+ var x = M.lookup x
+
+instance Expr (M.Map String Integer -> Maybe Integer) where
+ lit x = \_ -> Just x
+ add x y = \m -> case (x m) of
+ Just xv -> case (y m) of
+ Just yv -> Just (xv + yv)
+ Nothing -> Nothing
+ Nothing -> Nothing
+ mul x y = \m -> case (x m) of
+ Just xv -> case (y m) of
+ Just yv -> Just (xv * yv)
+ Nothing -> Nothing
+ Nothing -> Nothing
+
+withVars :: [(String, Integer)]
+ -> (M.Map String Integer -> Maybe Integer)
+ -> Maybe Integer
+withVars vs exp = exp $ M.fromList vs