Created
November 5, 2022 23:23
-
-
Save keyboard-slayer/f7ab175eb7a70524aa89b76c550025c8 to your computer and use it in GitHub Desktop.
Revisions
-
keyboard-slayer created this gist
Nov 5, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,61 @@ include "stdio"; include "stdlib"; enum Maybe[T] { Nothing, Just(T val), Maybe[U] operator>>=(Fn(T) -> Maybe[U]) { switch(this) { case Nothing: { return Nothing; } case Just(val): { return fn(val); } } } T unwrap(void) { switch(this) { case Nothing: { panic("Nothing to unwrap"); exit(1); } case Just(val): { return val; } } } } Maybe[double] safediv(double a, double b) { if (b == 0) { return Nothing; } else { return Just(a / b); } } int main(int argc, char const **argv) { Maybe[double] a = safediv(9, 2) >>= | x: double | { safediv(x, 2) }; // A little bit of monadic magic printf("%lf", a.unwrap()); return 0; }