Last active
December 15, 2020 20:10
-
-
Save vasilkosturski/ea0f7bc786ab1f1fdbe9b922030ab40a to your computer and use it in GitHub Desktop.
clash-of-styles-add-new-value-types
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
open System | |
type Value = | |
| MyInt of int | |
| MyRational of int * int | |
type Expression = | |
| MyValue of Value | |
| Addition of Expression * Expression | |
let rec addValues(op1, op2) = | |
match (op1, op2) with | |
| (MyInt i1, MyInt i2) -> MyInt(i1 + i2) | |
| (MyInt i, MyRational(num, den)) -> MyRational(i*den + num, den) | |
| (MyRational(_, _), MyInt _) -> addValues(op2, op1) | |
| (MyRational(num1, den1), MyRational(num2, den2)) -> MyRational(num1*den2 + num2*den1, den1*den2) | |
let rec eval expression = | |
match expression with | |
| MyValue v -> v | |
| Addition (op1, op2) -> addValues(eval op1, eval op2) | |
let stringifyValue v = | |
match v with | |
| MyInt i -> i.ToString() | |
| MyRational(num, den) -> num.ToString() + "/" + den.ToString() | |
let rec stringify expression = | |
match expression with | |
| MyValue v -> stringifyValue v | |
| Addition (op1, op2) -> stringify op1 + " + " + stringify op2 | |
[<EntryPoint>] | |
let main argv = | |
let expression = Addition(MyValue(MyInt 3), | |
Addition(MyValue(MyRational(2, 3)), MyValue(MyInt 5))) | |
let asString = stringify expression | |
let result = eval expression | |
Console.WriteLine(asString + " = " + stringifyValue result) // 3 + 2/3 + 5 = 26/3 | |
0 // return an integer exit code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I see you made
addValues
recursive to avoid repeating code. There is another way to do this using pattern matching: