Skip to content

Instantly share code, notes, and snippets.

@taku0
Created October 13, 2011 14:31
Show Gist options
  • Save taku0/1284349 to your computer and use it in GitHub Desktop.
Save taku0/1284349 to your computer and use it in GitHub Desktop.
数値がオブジェクトであるような体系で、同一でないオブジェクトが数値として等しくなる例
import java.util.concurrent.Callable;
public class Main {
public static void main(String[] args) {
Number two1 = new Succ(new Succ(new Zero()));
Number two2 = new Succ(new Succ(new Zero()));
System.out.println(two1 == two2);
System.out.println(two1.myEquals(two2));
}
}
interface MyBoolean {
public <T> T myIf(Callable<T> thenPart, Callable<T> elsePart) throws Exception;
public MyBoolean not();
}
class True implements MyBoolean {
public <T> T myIf(Callable<T> thenPart, Callable<T> elsePart) throws Exception {
return thenPart.call();
}
public MyBoolean not() {
return new False();
}
@Override
public String toString() {
return "True";
}
}
class False implements MyBoolean {
public <T> T myIf(Callable<T> thenPart, Callable<T> elsePart) throws Exception {
return elsePart.call();
}
public MyBoolean not() {
return new True();
}
@Override
public String toString() {
return "False";
}
}
interface Number {
public MyBoolean isZero();
public Number getPred();
public MyBoolean myEquals(Number other);
}
class Zero implements Number {
public MyBoolean isZero() {
return new True();
}
public Number getPred() {
throw new UnsupportedOperationException();
}
public MyBoolean myEquals(Number other) {
return other.isZero();
}
}
class Succ implements Number {
protected Number pred;
public Succ(Number pred) {
this.pred = pred;
}
public MyBoolean isZero() {
return new False();
}
public Number getPred() {
return pred;
}
public MyBoolean myEquals(final Number other) {
MyBoolean isOtherZero = other.isZero();
try {
return isOtherZero.myIf(new Callable<MyBoolean>() {
public MyBoolean call() {
return new False();
}
},
new Callable<MyBoolean>() {
public MyBoolean call() {
return getPred().myEquals(other.getPred());
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment