Skip to content

Instantly share code, notes, and snippets.

@alajpie
Created May 22, 2020 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alajpie/35d32eb5bf48c043d52e7f055ada0c63 to your computer and use it in GitHub Desktop.
Save alajpie/35d32eb5bf48c043d52e7f055ada0c63 to your computer and use it in GitHub Desktop.
#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