]> git.rkrishnan.org Git - yorgey.git/blob - hw5/Calc.hs
hw5: exercise 4
[yorgey.git] / hw5 / Calc.hs
1 {-# OPTIONS_GHC -Wall #-}
2
3 module Calc where
4
5 import ExprT
6 import Parser
7
8 eval :: ExprT -> Integer
9
10 -- exercise 1
11 eval (Lit n) = n
12 eval (Add e1 e2) = eval e1 + eval e2
13 eval (Mul e1 e2) = eval e1 * eval e2
14
15 -- exercise 2
16 evalStr :: String -> Maybe Integer
17 -- evalStr s = case (parseExp Lit Add Mul s) of
18 --               Just e -> Just (eval e)
19 --              Nothing -> Nothing
20 evalStr s = fmap eval (parseExp Lit Add Mul s)
21
22 class Expr a where
23   lit :: Integer -> a
24   add :: a -> a -> a
25   mul :: a -> a -> a
26
27 instance Expr ExprT where
28   lit = Lit
29   add = Add
30   mul = Mul
31
32 reify :: ExprT -> ExprT
33 reify = id
34
35 instance Expr Integer where
36   lit = id
37   add = (+)
38   mul = (-)
39
40 instance Expr Bool where
41   lit x | x <= 0 = False
42         | otherwise = True
43   add = (||)
44   mul = (&&)
45
46 newtype MinMax = MinMax Integer deriving (Show, Eq)
47
48 instance Expr MinMax where
49   lit = MinMax
50   add (MinMax x) (MinMax y) = MinMax (max x y)
51   mul (MinMax x) (MinMax y) = MinMax (min x y)
52
53 newtype Mod7 = Mod7 Integer deriving (Show, Eq)
54
55 instance Expr Mod7 where
56   lit x = Mod7 (x `mod` 7)
57   add (Mod7 x) (Mod7 y) = Mod7 ((x+y) `mod` 7)
58   mul (Mod7 x) (Mod7 y) = Mod7 ((x*y) `mod` 7)