Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Created April 16, 2022 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlhaufe/9cd847b364db31533619347bea6583d6 to your computer and use it in GitHub Desktop.
Save mlhaufe/9cd847b364db31533619347bea6583d6 to your computer and use it in GitHub Desktop.
Expression Problem
/** 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))
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