Skip to content

Instantly share code, notes, and snippets.

@manuel
Created September 16, 2010 15:17
Show Gist options
  • Save manuel/582590 to your computer and use it in GitHub Desktop.
Save manuel/582590 to your computer and use it in GitHub Desktop.
abstract class Term<T> {
abstract T eval();
}
class IntegerTerm extends Term<Integer> {
Integer value;
IntegerTerm(Integer value) { this.value = value; }
Integer eval() { return value; }
}
class StringTerm extends Term<String> {
String value;
StringTerm(String value) { this.value = value; }
String eval() { return value; }
}
class IsZeroTerm extends Term<Boolean> {
Term<Integer> subTerm;
IsZeroTerm(Term<Integer> subTerm) { this.subTerm = subTerm; }
Boolean eval() {
return subTerm.eval() == 0 ? true : false;
}
}
class IfTerm<T> extends Term<T> {
Term<Boolean> testTerm;
Term<T> thenTerm, elseTerm;
IfTerm(Term<Boolean> testTerm, Term<T> thenTerm, Term<T> elseTerm) {
this.testTerm = testTerm; this.thenTerm = thenTerm; this.elseTerm = elseTerm;
}
T eval() {
if (testTerm.eval())
return thenTerm.eval();
else
return elseTerm.eval();
}
}
public class GADT {
public static void main(String[] args) {
String result =
new IfTerm<String>(new IsZeroTerm(new IntegerTerm(12)),
new StringTerm("It's zero"),
new StringTerm("It's not zero")).eval();
System.out.println(result);
}
}
@jbgi
Copy link

jbgi commented May 7, 2015

alternative implementation that dissociate eval() from Term:
https://gist.github.com/jbgi/208a1733f15cdcf78eb5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment