Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 212
programmingSeemsFun Avatar asked Feb 28 '16 19:02

programmingSeemsFun


People also ask

How is a discriminated union defined?

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.

What is a union in f#?

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.


1 Answers

let sameLabels x y = 
    match x, y with
    | FirstLabel _ , FirstLabel _
    | SecondLabel _, SecondLabel _
    | ThirdLabel _ , ThirdLabel _  -> true
    | _ -> false
like image 97
Lee Avatar answered Oct 16 '22 07:10

Lee