sourcelib/Maybe.xtl
1⍝# Maybe: a value that may be missing, and the monad that chains
2⍝# computations which can fail (a standard library, built into xetal).
3⍝# Import it with an alias of your choice: "m:" u_se< "Maybe".
4⍝#
5⍝# A maybe is Church-encoded: it is a function of two arguments, what
6⍝# to give when it is empty and what to do with its value. n_othing
7⍝# gives the first; j_ust x applies the second to x.
8⍝#
9⍝# Like '+ r_/ A, the function comes first, as a quoted operand, so a
10⍝# chain reads right to left: 'g b_ind 'f b_ind m is f, then g.
11
12⍝## Making a maybe
13
14⍝# The empty maybe.
15⍝# >> "m:" u_se< "Maybe"
16⍝# >> 0 m:o_r 'm:n_othing
17⍝# 0
18ˡn̲othing ← { n j → n }
19
20⍝# A maybe holding x.
21⍝# >> "m:" u_se< "Maybe"
22⍝# >> 0 m:o_r m:j_ust 7
23⍝# 7
24ˡj̲ust ← { x n j̲ → j̲ x }
25
26⍝## Using a maybe
27
28⍝# d 'f m_aybe m: f applied to m's value, or d when m is empty.
29ˡm̲aybe ← { f̲ d m̲ → d m̲ 'f̲ }
30
31⍝# d o_r m: m's value, or d when m is empty.
32ˡo̲r ← { d m̲ → d m̲ '{ x → x } }
33
34⍝# 'f m_ap m: f applied inside the maybe; empty stays empty.
35ˡm̲ap ← { f̲ m̲ → 'ˡn̲othing m̲ '{ x → ˡj̲ust f̲ x } }
36
37⍝# 'f b_ind m: f (which gives a maybe) applied to m's value; empty
38⍝# stays empty, so a chain of steps stops at the first that fails.
39ˡb̲ind ← { f̲ m̲ → 'ˡn̲othing m̲ 'f̲ }