Skip to content

Instantly share code, notes, and snippets.

@keyboard-slayer
Created November 5, 2022 23:23
Show Gist options
  • Save keyboard-slayer/f7ab175eb7a70524aa89b76c550025c8 to your computer and use it in GitHub Desktop.
Save keyboard-slayer/f7ab175eb7a70524aa89b76c550025c8 to your computer and use it in GitHub Desktop.
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