From 9518f5edccf340f21fd891283b30de2112394fd8 Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan Date: Sun, 21 Dec 2014 21:51:10 +0530 Subject: [PATCH] hw5: exercise 6 --- hw5/Calc.hs | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) 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 -- 2.37.2