Created
September 8, 2023 00:42
-
-
Save mlhaufe/040426221fec63609821475f59769dd8 to your computer and use it in GitHub Desktop.
Trivial OO Expression Problem Solved in TypeScript
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
// 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