Skip to content

Instantly share code, notes, and snippets.

@lucamolteni
Created November 5, 2014 11:46
Show Gist options
  • Save lucamolteni/529be1def12e9faaa060 to your computer and use it in GitHub Desktop.
Save lucamolteni/529be1def12e9faaa060 to your computer and use it in GitHub Desktop.
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