Z
Z
zm_sansan2015-06-07 15:05:59
Functional programming
zm_sansan, 2015-06-07 15:05:59

How to know the constructor of an object and compare with another constructor in F#?

Suppose there is a type Type. A, A1, B, B1, B2, B, C are some types.
type Type = | Cons1 A A1 | Cons2 B B1 B2 | Cons3 C
And there is a function that takes two objects of type Type.
The function should return true if the object constructors are the same, false otherwise.
I couldn't find a function in F# to extract a constructor and compare it with another.
All sorts of manual enumeration of constructor combinations is too expensive in a real program, since there are many constructors.
Tell me if it is possible to implement this and if so, how, and if not, what workarounds exist.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
zm_sansan, 2015-06-07
@zm_sansan

Having learned the same constructors or not, I can judge that these objects are similar in their external structure, abstracting from the arguments.
Found a solution.

open Microsoft.FSharp.Reflection
let cons (x:'a) = ((FSharpValue.GetUnionFields(x, typeof<'a>)) |> fst).Name

M
Melz, 2015-06-07
@melz

To be honest, I can't imagine why this should be done in a functional language and how you are going to use the result. There will be a crutch on a crutch.
The easiest way is to make an interface and check whether its object implements something like this
let obj1 : obj = upcast (...)
match obj1 with
| :? ISomeInterface -> (do something)
| _ -> ()
Well, or just create a new "type" with goodies.
typeMixedType =
| Tup of int * int // a tuple
| P of Person // use the record type defined above
| L of int list // a list of ints
| U of IntOrBool // use the union type defined above
Well, under the word type in F # there are quite a lot of different things.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question