-
Notifications
You must be signed in to change notification settings - Fork 178
/
sumtypes.carp
82 lines (67 loc) · 1.54 KB
/
sumtypes.carp
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
73
74
75
76
77
78
79
80
81
82
(use Maybe)
(Project.no-echo)
(Project.config "print-ast" true)
;; Generic types
(defn generic-sumtypes [s]
(match s
(Maybe.Nothing) @"Nada"
(Maybe.Just x) (str* "Something like " (str x))
))
;; A more convenient syntax when doing C-style enums
(deftype Grade A B C)
(use Grade)
(defn grade-value [g]
(match (the Grade g)
A 20
B 15
C 10))
;; Figure out which type to use when some cases have the same name
(deftype Commands
StandGround
Fire
Retreat)
(deftype Elements
Water
Fire ;; <- name clash!
Earth
Air)
(use Commands)
(use Elements)
(defn figure-out-sumtype [x]
(match x
Fire (Water)
Air (Earth)))
;; Variable shadowing inside match
(defn confusion [x]
(match x
(Maybe.Just x) x
(Maybe.Nothing) @"Nope"))
;; Wildcards
(defn wildcard [x]
(match x
Nothing @"No"
_ @"Yes"
))
(deftype Name
(Simple [String String])
(Fancy [String String String]))
(use Name)
(defn wildcards-inside [name]
(match name
(Simple _ _) 1
(Fancy _ _ _) 2))
;; Recursive sumtype
;; (deftype JSON
;; (Str [String])
;; (Num [Double])
;; (Arr [(Array JSON)])
;; (Obj [(Map String JSON)]))
(defn main []
(do
(println* (generic-sumtypes (Maybe.Just 123)))
(println* (generic-sumtypes (the (Maybe Int) (Maybe.Nothing))))
(println* &(figure-out-sumtype (Elements.Fire)))
(println* "Grade.B has value " (grade-value (Grade.B)))
(println* (confusion (Just @"Yo")))
(println* (wildcard (Just @"Woop")))
(println* (wildcards-inside (Simple @"Erik" @"Svedäng")))))