Monads/Maybe monad: Difference between revisions
Content added Content deleted
Line 305: | Line 305: | ||
{missing value, missing value, missing value, missing value, 0.5, 0.0, -0.346573590279, -0.499999999999, -0.549306144333, -0.69314718056, -0.804718956217}</pre> |
{missing value, missing value, missing value, missing value, 0.5, 0.0, -0.346573590279, -0.499999999999, -0.549306144333, -0.69314718056, -0.804718956217}</pre> |
||
=={{header|ATS}}== |
|||
<syntaxhighlight lang="ats"> |
|||
#include "share/atspre_staload.hats" |
|||
(* There are "Option" and "Option_vt" in the ATS2 prelude, but I shall |
|||
construct something anew. *) |
|||
datatype Maybe (a : t@ype+) = |
|||
| Nothing of () |
|||
| Just of a |
|||
fn {a, b : t@ype} |
|||
bind_Maybe {u : bool} |
|||
(m : Maybe a, |
|||
f : a -<cloref1> Maybe b) : Maybe b = |
|||
case+ m of |
|||
| Nothing {a} () => Nothing {b} () |
|||
| Just {a} x => f x |
|||
infixl 0 >>= |
|||
overload >>= with bind_Maybe |
|||
implement |
|||
main0 () = |
|||
let |
|||
val f : int -<cloref1> Maybe int = |
|||
lam i =<cloref1> if (i : int) < 0 then Nothing () else Just i |
|||
val g : int -<cloref1> Maybe string = |
|||
lam i =<cloref1> Just (tostring_val<int> i) |
|||
in |
|||
case+ Just 123 >>= f >>= g of |
|||
| Nothing () => println! ("Nothing ()") |
|||
| Just s => println! ("Just (\"", s : string, "\")"); |
|||
case+ Just ~123 >>= f >>= g of |
|||
| Nothing () => println! ("Nothing ()") |
|||
| Just s => println! ("Just (\"", s : string, "\")") |
|||
end |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ patscc -std=gnu2x -g -O2 -DATS_MEMALLOC_GCBDW maybe_monad_ats.dats -lgc && ./a.out |
|||
Just ("123") |
|||
Nothing ()</pre> |
|||
=={{header|C}}== |
=={{header|C}}== |