summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEdoardo La Greca2025-07-10 01:10:28 +0200
committerEdoardo La Greca2025-07-10 01:10:28 +0200
commit9bd2d97f9172581064890af803134d99a1251678 (patch)
treebb7c836806b6dc4095f3ff67eeca8bf39191b716
parent2b6de7cb0402e67dd8792d45a9466d7b085666af (diff)
add fourth exercise of lecture 5HEADmaster
-rw-r--r--lec05/Calc.hs35
1 files changed, 35 insertions, 0 deletions
diff --git a/lec05/Calc.hs b/lec05/Calc.hs
index f97d784..7502b5f 100644
--- a/lec05/Calc.hs
+++ b/lec05/Calc.hs
@@ -31,3 +31,38 @@ instance Expr ExprT where
reify :: ExprT -> ExprT
reify = id
+
+-- Exercise 4
+
+instance Expr Integer where
+ lit x = x
+ add l r = eval (Add (Lit l) (Lit r))
+ mul l r = eval (Mul (Lit l) (Lit r))
+
+instance Expr Bool where
+ lit x
+ | x <= 0 = False
+ | otherwise = True
+ add = (||)
+ mul = (&&)
+
+newtype MinMax = MinMax Integer deriving (Eq, Show)
+newtype Mod7 = Mod7 Integer deriving (Eq, Show)
+
+instance Expr MinMax where
+ lit = MinMax
+ add (MinMax l) (MinMax r) = MinMax (max l r)
+ mul (MinMax l) (MinMax r) = MinMax (min l r)
+
+instance Expr Mod7 where
+ lit x = Mod7 (mod x 7)
+ add (Mod7 l) (Mod7 r) = Mod7 (mod (l + r) 7)
+ mul (Mod7 l) (Mod7 r) = Mod7 (mod (l * r) 7)
+
+testExp :: Expr a => Maybe a
+testExp = parseExp lit add mul "(3 * -4) + 5"
+
+testInteger = testExp :: Maybe Integer
+testBool = testExp :: Maybe Bool
+testMM = testExp :: Maybe MinMax
+testSat = testExp :: Maybe Mod7