-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlang_demo.hs
72 lines (51 loc) · 1.71 KB
/
lang_demo.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
{-#LANGUAGE TypeFamilies #-}
module LangDemo where
-- If you never change the base value and are only adding expressions
data BaseVal = IntV Int
data BaseExp = ValE BaseVal
| AddE BaseExp BaseExp
data ExtExp = BaseE BaseExp
| SubE ExtExp ExtExp
class Lang lang where
eval :: lang -> BaseVal
instance Lang BaseExp where
eval (ValE i) = i
eval (AddE be1 be2) =
let IntV i1 = eval be1
IntV i2 = eval be2
in IntV $ i1 + i2
instance Lang ExtExp where
eval (BaseE b) = eval b
eval (SubE ee1 ee2) =
let IntV i1 = eval ee1
IntV i2 = eval ee2
in IntV $ i1 - i2
-- if you want to be able to change the set of values you can evaluate to when extending the language
data BaseVal2 = IntV2 Int
data BaseExp2 = ValBE2 BaseVal2
| AddE2 BaseExp2 BaseExp2
data ExtVal2 = StringV2 String
data ExtExp2 = BaseE2 BaseExp2
| ValEE2 ExtVal2
| ConcatE2 ExtExp2 ExtExp2
-- can use type families to suspend the value kind until later.
data family Val2
class Lang2 lang where
eval :: lang -> Val2
-- define at some time t1 for the base language
data instance Val2 = BV2 BaseVal2
instance Lang2 BaseExp2 where
eval ValBE2 bv2 = BV2 bv2
eval AddE2 be1 be2 =
let IntV2 i1 = eval be1
IntV2 i2 = eval be2
in BV2 $ IntV2 $ i1 + i2
-- extend at some later time t2 for the extended language
data instance Val2 = EV2 ExtVal2
instance Lang2 ExtExp2 where
eval BaseE2 be2 = eval be2
eval ValEE2 ev2 = ev2
eval ConcatE2 ee1 ee2 =
case (eval ee1, eval ee2) of
(StringV2 s1, StringV2 s2) -> EV2 $ StringV2 $ s1 ++ s2
_ -> error "trying to concat something other than strings!"