Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Created September 8, 2023 00:42
Show Gist options
  • Save mlhaufe/040426221fec63609821475f59769dd8 to your computer and use it in GitHub Desktop.
Save mlhaufe/040426221fec63609821475f59769dd8 to your computer and use it in GitHub Desktop.
Trivial OO Expression Problem Solved in TypeScript
// See the following for a Scala example: <https://i.cs.hku.hk/~bruno/papers/Modularity2016.pdf>
/* Initial code */
abstract class Exp { abstract evaluate(): number }
class Lit extends Exp {
constructor(readonly x: number){ super(); }
evaluate(): number { return this.x }
}
class Add extends Exp {
constructor(readonly left: Exp, readonly right: Exp) { super() }
evaluate(): number {
return this.left.evaluate() + this.right.evaluate()
}
}
/* Adding new operation 'print' */
abstract class ExpP extends Exp { abstract print(): string }
class LitP extends Lit implements ExpP {
print(): string { return this.x.toString() }
}
class AddP extends Add implements ExpP {
// Note the type refinement on the properties
constructor(readonly left: ExpP, readonly right: ExpP) { super(left, right) }
print(): string {
return this.left.print() + this.right.print()
}
}
/* Adding new variant 'Sub' */
class Sub extends Exp {
constructor(readonly left: Exp, readonly right: Exp) { super() }
evaluate(): number {
return this.left.evaluate() - this.right.evaluate()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment