Created
November 5, 2014 11:46
-
-
Save lucamolteni/23963d5843c4f2256a0a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public class CategoryTheory { | |
public static <T> Function<T, T> id() { | |
return new Function<T, T>() { | |
@Override | |
public T apply(T arg) { | |
return arg; | |
} | |
}; | |
} | |
interface Function<A, B> { | |
public B apply(A arg); | |
} | |
public static <A, B, C> Function<A, C> compose(final Function<A, B> f, final Function<B, C> g) { | |
return new Function<A, C>() { | |
@Override | |
public C apply(A arg) { | |
return g.apply(f.apply(arg)); | |
} | |
}; | |
} | |
public static void main(String[] args) { | |
Object a = id().apply(2); | |
System.out.println("a = " + a); | |
Function<Object, Object> increment = new Function<Object, Object>() { | |
@Override | |
public Object apply(Object arg) { | |
return (Integer)arg + 1; | |
} | |
}; | |
Function<Object, Object> show = new Function<Object, Object>() { | |
@Override | |
public Object apply(Object arg) { | |
return arg.toString(); | |
} | |
}; | |
Function<Object, Object> incrementThenShow = compose(increment, show); | |
System.out.println("incrementThenShow.apply(2) = " + incrementThenShow.apply(2)); | |
// f . id == f | |
Function<Object, Object> five = new Function<Object, Object>() { | |
@Override | |
public Object apply(Object arg) { | |
return 5; | |
} | |
}; | |
Object res = compose(id(), five).apply("any"); | |
System.out.println("res = " + res); | |
// id . f == f | |
Object res2 = compose(five, id()).apply("any"); | |
System.out.println("res = " + res2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment