Skip to content

Instantly share code, notes, and snippets.

@vasilkosturski
Last active December 15, 2020 20:10
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 vasilkosturski/ea0f7bc786ab1f1fdbe9b922030ab40a to your computer and use it in GitHub Desktop.
Save vasilkosturski/ea0f7bc786ab1f1fdbe9b922030ab40a to your computer and use it in GitHub Desktop.
clash-of-styles-add-new-value-types
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
@amieres
Copy link

amieres commented Dec 15, 2020

I see you made addValues recursive to avoid repeating code. There is another way to do this using pattern matching:

let addValues(op1, op2) =
    match    (op1, op2) with
    | MyInt      i1         , MyInt      i2           -> MyInt(i1 + i2)
    | MyRational(num , den ), MyInt      i
    | MyInt      i          , MyRational(num , den )) -> MyRational(   i*den  + num      , den      )
    | MyRational(num1, den1), MyRational(num2, den2)) -> MyRational(num1*den2 + num2*den1, den1*den2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment