F # comparison of discriminated associations by case identifier

Is there a way to compare discriminated unions with my case identifiers in F #?

type MyUnion =
| MyString of string
| MyInt of int

let x = MyString("hello")
let y = MyString("bye")
let z = MyInt(25)

let compareCases a b =
// compareCases x y = true
// compareCases x z = false
// compareCases y z = false

How to implement a function in a compareCasesgeneral way?

those. something like the following, but more general (reflection in order):

let compareCases a b =
  match a with
  | MyString(_) -> match b with | MyString(_) -> true | _ -> false
  | MyInt(_) -> match b with | MyInt(_) -> true | _ -> false
+3
source share
4 answers

The problem with using GetType () is that it fails if you have 2 "no data" cases.

Here is one way to do this: (Edited because the previous UnionTagReader was not cached)

type MyDU =
    | Case1
    | Case2
    | Case3 of int
    | Case4 of int

type TagReader<'T>() =
    let tr = 
        assert FSharpType.IsUnion(typeof<'T>)
        FSharpValue.PreComputeUnionTagReader(typeof<'T>, System.Reflection.BindingFlags.Public)

    member this.compareCase (x:'T) (y:'T) =
        (tr x) = (tr y)

let tr = TagReader<MyDU>()

let c1 = Case1
let c2 = Case2
let c3 = Case3(0)
let c3' = Case3(1)
let c4 = Case4(0)

assert (c1.GetType() = c2.GetType() )  //this is why you can not use GetType()

assert tr.compareCase c1 c1
assert not (tr.compareCase c1 c2)
assert tr.compareCase c3 c3'
assert not (tr.compareCase c3 c4)
+5
source

First of all, you can improve your example as follows:

let compare = function
| MyString _, MyString _, | MyInt _, MyInt _ -> true
| _ -> false

( !):

let compare a b = a.GetType () = b.GetType ()
+3

That should do the trick

open Microsoft.FSharp.Reflection

type MyUnion =
    | MyString of string
    | MyInt of int

let x = MyString("hello")
let y = MyString("bye")
let z = MyInt(25)

let compareCases a b =
    FSharpValue.GetUnionFields (a, a.GetType()) |> fst
        = (FSharpValue.GetUnionFields (b, b.GetType()) |> fst)

although in order to do anything with values, you still have to match patterns, so I don’t quite understand, to be honest.

0
source
let compareCases (a : MyUnion) (b : MyUnion) =
    a.GetType().Name = b.GetType().Name
0
source

Source: https://habr.com/ru/post/1544566/


All Articles