#include <stdbool.h> | |
#include <stdio.h> | |
// only on ints cause lol no generics in C | |
typedef struct optional { | |
bool exists; | |
int value; | |
} optional; | |
optional functor(int (*f)(int), optional x) { | |
if (x.exists) { | |
return (optional){true, f(x.value)}; | |
} else { | |
return (optional){false, 0}; | |
} | |
} | |
optional monad(optional (*f)(int), optional x) { | |
if (x.exists) { | |
return f(x.value); | |
} else { | |
return (optional){false, 0}; | |
} | |
} | |
int square(int n) { return n * n; } | |
optional square_positives(int n) { | |
if (n > 0) { | |
return (optional){true, n * n}; | |
} else { | |
return (optional){false, 0}; | |
} | |
} | |
void pretty_print(optional x) { | |
if (x.exists) { | |
printf("Just %i\n", x.value); | |
} else { | |
printf("Nothing\n"); | |
} | |
} | |
int main() { | |
optional a = {true, -2}; | |
pretty_print(a); // Just -2 | |
optional b = {false, 0}; | |
pretty_print(b); // Nothing | |
optional c = functor(square, a); | |
pretty_print(c); // Just 4 | |
optional d = functor(square, b); | |
pretty_print(d); // Nothing | |
optional e = monad(square_positives, a); | |
pretty_print(e); // Nothing | |
optional f = monad(square_positives, b); | |
pretty_print(f); // Nothing | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment