-
Notifications
You must be signed in to change notification settings - Fork 3
/
mdo-macros.fnl
65 lines (58 loc) · 1.54 KB
/
mdo-macros.fnl
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
;; fennel-ls: macro-file
(fn mdo [dMonad ...]
"Haskell's do notation"
;;; Reverse the instructions
(local instructions [...])
(let [len (length instructions)]
(for [i (- len 1) 1 (- 1)]
(tset instructions
len
(table.remove instructions i))))
;;; Generate symbols for bind and pure
(local syms
{:>>= (gensym :_>>=)
:pure (gensym :_pure)})
(var res nil)
(match instructions
;;; Last (now first) instruction is used as a result
(where [result & instrs] (= :table (type result)))
(do
(set res result)
(each [_ instr (ipairs instrs)]
(match instr
;;; Bind (<- x mx)
(where [[:<- nil] [x nil] mx nil]
(= :string (type x)))
(do
(set res `(,syms.>>= ,mx (fn [,(sym x)] ,res))))
;;; Ignore Bind (lone expression)
[mx]
(do
(set res `(,syms.>>= ,mx (fn [_#] ,res)))))))
;;; Invalid form (no last instruction)
_
(do
(assert-compile false "Invalid form" [...])))
;;; Output binds the used bind and pure functions
`(when true
(let [{:>>= ,syms.>>=
:pure ,syms.pure} ,dMonad]
,res)))
;; (fn safe-div [x y]
;; (if (= (% x y) 0)
;; (Option.some (/ x y))
;; (Option.none)))
;;
;; (print
;; (mdo Option
;; (<- a (Option.some 4))
;; (<- a (safe-div a 2))
;; (<- a (safe-div a 2))
;; (Option.pure a)))
;;
;; (macrodebug
;; (mdo Option
;; (<- a (f a b))
;; (mqu a b c)
;; (pure mb)))
{: mdo}