Last active
July 21, 2022 08:59
-
-
Save papayankey/d0daefb8d707d6bc79a03a1cc05242a0 to your computer and use it in GitHub Desktop.
Pattern matching using discriminate union
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
| // Discriminated Union ( pattern matching ) | |
| type Operator = 'add' | 'sub' | 'mul' | 'div'; | |
| type Num = { | |
| kind: 'number' | |
| value: number | |
| } | |
| type Operation = { | |
| kind: Operator | |
| first: Expression | |
| second: Expression | |
| } | |
| type Expression = Num | Operation; | |
| // factory object to create a Num type | |
| function num(value: number): Num { | |
| return { | |
| kind: 'number', | |
| value | |
| }; | |
| } | |
| // factory object to create an operator type | |
| function op(first: Expression, second: Expression, kind: Operator): Expression { | |
| return { | |
| kind, | |
| first, | |
| second | |
| }; | |
| } | |
| function evaluate(expr: Expression): number { | |
| switch(expr.kind) { | |
| case 'number': return expr.value; | |
| case 'add': return evaluate(expr.first) + evaluate(expr.second); | |
| case 'sub': return evaluate(expr.first) - evaluate(expr.second); | |
| case 'mul': return evaluate(expr.first) * evaluate(expr.second); | |
| case 'div': return evaluate(expr.first) / evaluate(expr.second); | |
| } | |
| } | |
| evaluate(op(num(15), op(num(3), num(3), 'mul'), 'sub')); // 6 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment