Skip to content

Instantly share code, notes, and snippets.

@keyboard-slayer
Created November 5, 2022 23:23
Show Gist options
  • Select an option

  • Save keyboard-slayer/f7ab175eb7a70524aa89b76c550025c8 to your computer and use it in GitHub Desktop.

Select an option

Save keyboard-slayer/f7ab175eb7a70524aa89b76c550025c8 to your computer and use it in GitHub Desktop.

Revisions

  1. keyboard-slayer created this gist Nov 5, 2022.
    61 changes: 61 additions & 0 deletions dream.c
    Original 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;
    }