Created
September 16, 2010 15:17
-
-
Save manuel/582590 to your computer and use it in GitHub Desktop.
This file contains 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
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alternative implementation that dissociate eval() from Term:
https://gist.github.com/jbgi/208a1733f15cdcf78eb5