An implementation of the Maybe monad in Java for instructional purposes.
import java.util.function.Function; | |
// Maybe is a monad. Why is it a monad? It is a monad because it: | |
// A) wraps a value | |
// B) provides a way of applying functions/calling methods on the wrapped value | |
// C) always returns an instance of itself when it does this. | |
class Maybe<T> { | |
private T value; | |
public Maybe(T value) { | |
this.value = value; // This satisfies A from above | |
} | |
// map takes a function and applies it to the wrapped value, | |
// but only when the wrapped value is not null. | |
// This satisfies B from above. | |
// Since the only returns are this (an instance of the Maybe), | |
// and a new Maybe, this is guaranteed to return an instance | |
// of itself, thereby satisfying C from above. | |
public Maybe<T> map(Function<T, T> f) { | |
if(this.value == null) { | |
return this; | |
} else { | |
return new Maybe<T>(f.apply(this.value)); | |
} | |
} | |
public T value() { | |
return this.value; | |
} | |
} | |
public class What { | |
public static void main(String[] args) { | |
Function<Integer, Integer> doub = (x) -> (2*x); | |
Function<Integer, Integer> inc = (x) -> (x+1); | |
Function<Integer, Integer> returns_null = (x) -> (null); | |
Maybe<Integer> m; | |
Object output; | |
m = new Maybe<Integer>(3); // since m is wrapping 3, it will | |
output = m.map(doub).map(inc).value(); // simply apply doub and inc to it | |
System.out.println(output); // resulting in 2*3+1, or 7. | |
// prints 7 | |
m = new Maybe<Integer>(null); // since m is wrapping null, it will | |
output = m.map(doub).map(inc).value(); // happily skip function application | |
System.out.println(output); // and keep returning itself | |
// prints null | |
m = new Maybe<Integer>(13); // this will double 13, and then | |
output = m.map(doub).map(returns_null).map(inc).value(); // apply a function that returns null, | |
System.out.println(output); // after which it will skip any future | |
// prints null // function application safely. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment