Let's say we've got a uniontype in F#:
type Example =
|FirstLabel of int
|SecondLabel of int
|ThirdLabel of int
How could you create a function, which takes 2 parameters of the type "Example" and returns true, if the two parameters share the same label and else returns false? I want this function to return these results regardless of the value of the integers.
So if we have parameter1 and parameter2 with
val parameter1 : Example = SecondLabel 2
and
val parameter2 : Example = Secondlabel 5
the function would return true
I could not find an answer for this question even by searching thoroughly. Maybe I searched wrongly. So could you also give me a source for solving such problems?
A discriminated union is a union data structure that holds various objects, with one of the objects identified directly by a discriminant. The discriminant is the first item to be serialized or deserialized. A discriminated union includes both a discriminant and a component.
In F#, a sum type is called a “discriminated union” type. Each component type (called a union case) must be tagged with a label (called a case identifier or tag) so that they can be told apart (“discriminated”). The labels can be any identifier you like, but must start with an uppercase letter.
let sameLabels x y =
match x, y with
| FirstLabel _ , FirstLabel _
| SecondLabel _, SecondLabel _
| ThirdLabel _ , ThirdLabel _ -> true
| _ -> false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With