Created
December 13, 2013 09:14
-
-
Save rgantt/7941759 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ryangantt.monad; | |
/** | |
* Implementation of the identity monad | |
*/ | |
public class Identity<T> { | |
public T value; | |
public T getValue() { | |
return value; | |
} | |
public void setValue(final T value) { | |
this.value = value; | |
} | |
public String toString() { | |
return String.valueOf(value); | |
} | |
public Identity(final T value) { | |
setValue(value); | |
} | |
/** | |
* Factories | |
*/ | |
private static interface Func<K, U> { | |
public U apply(final K value); | |
} | |
public static <T, U> Identity<U> bind(final Identity<T> id, final Func<T, Identity<U>> k) { | |
return k.apply(id.getValue()); | |
} | |
public static <T> Identity<T> unit(final T value) { | |
return new Identity<T>(value); | |
} | |
/** | |
* Test | |
*/ | |
public static void main(final String[] args) { | |
final Identity<Integer> result = Identity.bind(unit(5), new Func<Integer, Identity<Integer>>() { | |
@Override | |
public Identity<Integer> apply(final Integer x) { | |
return bind(unit(6), new Func<Integer, Identity<Integer>>() { | |
@Override | |
public Identity<Integer> apply(final Integer y) { | |
return unit(x + y); | |
} | |
}); | |
} | |
}); | |
System.out.println("Result: " + result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment