Carp/examples/sumtypes.carp

83 lines
1.5 KiB
Plaintext
Raw Normal View History

2019-02-01 17:02:10 +03:00
(use Maybe)
(Project.no-echo)
(Project.config "print-ast" true)
2019-02-01 17:02:10 +03:00
;; 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)
2019-02-05 13:52:42 +03:00
(use Grade)
2019-02-05 13:52:42 +03:00
(defn grade-value [g]
(match (the Grade g)
A 20
B 15
C 10))
2019-02-05 13:52:42 +03:00
2019-02-11 18:28:42 +03:00
;; 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)))
2019-02-01 17:04:23 +03:00
;; Variable shadowing inside match
2019-02-01 17:02:10 +03:00
(defn confusion [x]
(match x
(Maybe.Just x) x
(Maybe.Nothing) @"Nope"))
;; Wildcards
(defn wildcard [x]
(match x
Nothing @"No"
2019-02-13 01:01:33 +03:00
_ @"Yes"
))
(deftype Name
(Simple [String String])
(Fancy [String String String]))
(use Name)
(defn wildcards-inside [name]
(match name
(Simple _ _) 1
(Fancy _ _ _) 2))
2019-02-05 13:37:44 +03:00
;; Recursive sumtype
2019-02-05 13:52:42 +03:00
;; (deftype JSON
;; (Str [String])
;; (Num [Double])
;; (Arr [(Array JSON)])
;; (Obj [(Map String JSON)]))
2019-02-05 13:37:44 +03:00
2019-02-01 17:02:10 +03:00
(defn main []
2019-02-05 13:52:42 +03:00
(do
(println* (generic-sumtypes (Maybe.Just 123)))
(println* (generic-sumtypes (the (Maybe Int) (Maybe.Nothing))))
2019-02-11 18:28:42 +03:00
(println* &(figure-out-sumtype (Elements.Fire)))
2019-02-05 13:52:42 +03:00
(println* "Grade.B has value " (grade-value (Grade.B)))
(println* (confusion (Just @"Yo")))
(println* (wildcard (Just @"Woop")))
(println* (wildcards-inside (Simple @"Erik" @"Svedäng")))))