Created
April 16, 2022 03:37
-
-
Save mlhaufe/9cd847b364db31533619347bea6583d6 to your computer and use it in GitHub Desktop.
Expression Problem
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
/** Number Expressions */ | |
// data | |
type Exp = | |
{ tag: 'Lit', value: number } | | |
{ tag: 'Add', left: Exp, right: Exp } | |
// operations | |
function evaluate(exp: Exp): number { | |
switch (exp.tag) { | |
case 'Lit': | |
return exp.value; | |
case 'Add': | |
return evaluate(exp.left) + evaluate(exp.right) | |
} | |
} | |
function print(exp: Exp): string { | |
switch (exp.tag) { | |
case 'Lit': | |
return `Lit(${exp.value})`; | |
case 'Add': | |
return `Add(${print(exp.left)},${print(exp.right)})` | |
} | |
} | |
// 1 + 3 | |
let exp: Exp = { | |
tag: 'Add', | |
left: { tag: 'Lit', value: 1 }, | |
right: { tag: 'Lit', value: 3 } | |
} | |
evaluate(exp) //4 | |
print(exp) // Add(Lit(1),Lit(3)) |
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 Exp { | |
abstract print(): string | |
abstract evaluate(): number | |
} | |
class Lit extends Exp { | |
// data | |
constructor(readonly value: number) { super() } | |
//operations | |
evaluate(): number { return this.value } | |
print(): string { return `Lit(${this.value})` } | |
} | |
class Add implements Exp { | |
// data | |
constructor(readonly left: Exp, readonly right: Exp) { } | |
// operations | |
evaluate(): number { | |
return this.left.evaluate() + this.right.evaluate() | |
} | |
print(): string { | |
return `Add(${this.left.print()},${this.right.print()})` | |
} | |
} | |
// 1 + 3 | |
let exp: Exp = new Add( | |
new Lit(1), | |
new Lit(3) | |
) | |
exp.evaluate() // 4 | |
exp.print() // Add(Lit(1),Lit(3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment