Created
November 5, 2022 23:23
-
-
Save keyboard-slayer/f7ab175eb7a70524aa89b76c550025c8 to your computer and use it in GitHub Desktop.
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 characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment