Created
December 27, 2013 20:54
-
-
Save startling/8152500 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 final class Nat { | |
private final Nat predecessor; | |
private Nat (Nat n) { | |
predecessor = null; | |
} | |
public static Nat S(Nat n) { | |
return new Nat(n); | |
} | |
public static Nat Z = new Nat(null); | |
public interface Eliminator<A> { | |
public A Z(); | |
public A S(A a); | |
} | |
public class Eliminate<A> { | |
private Eliminator<A> eliminator; | |
public Eliminate(Eliminator<A> e) { | |
eliminator = e; | |
} | |
public A call(Nat n) { | |
A v = eliminator.Z(); | |
while (n.predecessor != null) { | |
v = eliminator.S(v); | |
n = n.predecessor; | |
} | |
return v; | |
} | |
} | |
public boolean equals(Nat n) { | |
return predecessor == n.predecessor | |
|| predecessor.equals(n.predecessor); | |
} | |
private class ToInteger implements Eliminator<Integer> { | |
public Integer Z() { | |
return 0; | |
} | |
public Integer S(Integer n) { | |
return n + 1; | |
} | |
} | |
public Integer toInteger() { | |
Eliminate<Integer> e = new Eliminate(new ToInteger()); | |
return e.call(this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment