Skip to content

Instantly share code, notes, and snippets.

@tyler569
Created January 12, 2020 18:50
Show Gist options
  • Save tyler569/39bc5aadaec236108d4666b754d17b84 to your computer and use it in GitHub Desktop.
Save tyler569/39bc5aadaec236108d4666b754d17b84 to your computer and use it in GitHub Desktop.
import java.util.function.*;
interface Monad<T> {
Monad<T> bind(Function<T, Monad<T>> fn);
}
class maybe<T> implements Monad<T> {
boolean valid;
T value;
maybe(boolean v, T val) {
valid = v;
value = val;
}
maybe() {
valid = false;
value = null;
}
public Monad<T> bind(Function<T, Monad<T>> fn) {
if (valid) {
return fn.apply(value);
} else {
return None();
}
}
public static <U> maybe<U> Just(U value) {
return new maybe<U>(true, value);
}
public static <U> maybe<U> None() {
return new maybe<U>();
}
public String toString() {
if (valid) {
return "Some(" + value.toString() + ")";
} else {
return "None()";
}
}
}
public class monad {
static maybe<Integer> incEven(Integer j) {
if (j % 2 == 0) {
return maybe.None();
} else {
return maybe.Just(j + 1);
}
}
static maybe<Integer> half(Integer j) {
return maybe.Just(j / 2);
}
public static void main(String[] args) {
for (int i=0; i<20; i++) {
Monad<Integer> some = maybe.Just(i);
Monad<Integer> g = some.bind((j) -> incEven(j));
Monad<Integer> h = g.bind((j) -> half(j));
Monad<Integer> k = h.bind((j) -> incEven(j));
System.out.println(k);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment