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: given the two continuations, it takes the first and 15⍝│ drops the second (▁). 16⍝│ >> "m:" u_se< "Maybe" 17⍝│ >> 0 m:o_r 'm:n_othing 18⍝│ 0 19ˡn̲othing ← { n ▁ → n } 20 21⍝│ A maybe holding x: it drops the first continuation and hands x to 22⍝│ the second. 23⍝│ >> "m:" u_se< "Maybe" 24⍝│ >> 0 m:o_r m:j_ust 7 25⍝│ 7 26ˡj̲ust ← { x ▁ j̲ → j̲ x } 27 28⍝━━ Using a maybe 29 30⍝│ d 'f m_aybe m: f applied to m's value, or d when m is empty. 31ˡm̲aybe ← { f̲ d m̲ → d m̲ 'f̲ } 32 33⍝│ d o_r m: m's value, or d when m is empty. 34ˡo̲r ← { d m̲ → d m̲ 'i̲d } 35 36⍝│ 'f m_ap m: f applied inside the maybe; empty stays empty. 37ˡm̲ap ← { f̲ m̲ → 'ˡn̲othing m̲ '{ x → ˡj̲ust f̲ x } } 38 39⍝│ 'f b_ind m: f (which gives a maybe) applied to m's value; empty 40⍝│ stays empty, so a chain of steps stops at the first that fails. 41ˡb̲ind ← { f̲ m̲ → 'ˡn̲othing m̲ 'f̲ }