From: Ramakrishnan Muthukrishnan Date: Sun, 21 Dec 2014 16:21:10 +0000 (+0530) Subject: hw5: exercise 6 X-Git-Url: https://git.rkrishnan.org/(%5B%5E?a=commitdiff_plain;h=9518f5edccf340f21fd891283b30de2112394fd8;p=yorgey.git hw5: exercise 6 --- diff --git a/hw5/Calc.hs b/hw5/Calc.hs index edc0179..0e50663 100644 --- a/hw5/Calc.hs +++ b/hw5/Calc.hs @@ -8,7 +8,7 @@ module Calc where import qualified ExprT as E import Parser import StackVM - +import qualified Data.Map as M -- exercise 1 @@ -70,3 +70,42 @@ instance Expr Program where 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