Search code examples
f#discriminated-union

How to make a function which checks, if the labels of discriminated unions match?


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?


Solution

  • let sameLabels x y = 
        match x, y with
        | FirstLabel _ , FirstLabel _
        | SecondLabel _, SecondLabel _
        | ThirdLabel _ , ThirdLabel _  -> true
        | _ -> false