Created
October 19, 2016 04:46
-
-
Save mlhaufe/88d850328197debf67e2ca03bbfcd55e to your computer and use it in GitHub Desktop.
Term Evaluation in Pure OO style
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
abstract class Term<T> { | |
abstract eval() : T | |
} | |
class Lit extends Term<number> { | |
constructor(public value: number) { super() } | |
eval() : number { return this.value } | |
} | |
class Inc extends Term<number> { | |
constructor(public term: Term<number>) { super() } | |
eval() : number { return this.term.eval() + 1 } | |
} | |
class IsZ extends Term<boolean> { | |
constructor(public term: Term<number>) { super() } | |
eval() : boolean { return this.term.eval() == 0 } | |
} | |
class If<T> extends Term<T> { | |
constructor( | |
public pred: Term<boolean>, | |
public tCond: Term<T>, | |
public fCond : Term<T> | |
) { super() } | |
eval(): T { | |
return this.pred.eval() ? this.tCond.eval() : this.fCond.eval() | |
} | |
} | |
class Pair<A, B> extends Term<[A, B]> { | |
constructor(public left: Term<A>, public right: Term<B>) { super() } | |
eval() : [A,B] { return [this.left.eval(), this.right.eval()] } | |
} | |
class Fst<A, B> extends Term<A> { | |
constructor(public pair: Pair<A, B>) { super() } | |
eval() : A { return this.pair.left.eval() } | |
} | |
class Snd<A, B> extends Term<B> { | |
constructor(public pair: Pair<A, B>) { super() } | |
eval() : B { return this.pair.right.eval() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment