How to refer to the first element of a tuple encapsulated in a monotonous discriminatory union

Suppose you have a type like this:

type Corner = Corner of int*int 

and then some variable:

 let corner = Corner (1,1) 

Is it possible to get the value of the first element of a tuple, for example:

 fst corner 

It looks like some kind of reversal to int*int needed.

+5
source share
3 answers

The answer provided by @Foole is good, but the comment gives the impression that you don't like to β€œdeclare” the temporary variable first . It can really seem cumbersome if all you want to do is pull out the first value and then pass it to another function.

There is no built-in object that I know about that allows you to do this automatically. Suppose the above type of Corner is a degenerate case of the Discriminatory Union (DU). Usually DUs have more cases, and they are often heterogeneous in shape.

There may be good reasons for having the same DU, such as Corner , but it often makes sense to also provide various β€œhelper” functions to make working with this type smoother.

In the case of the Corner type, you can define functions such as:

 let cornerX (Corner(x, _)) = x let cornerY (Corner(_, y)) = y 

Here, I suggested that Corner models the coordinate, but if you want, you can also name the functions fst and snd . You can also put them in a dedicated module if you prefer this.

This will allow you to retrieve and pass the value from the Corner value without the hassle of a temporary variable:

 > corner |> cornerX |> ((*) 10) |> string;; val it : string = "10" 

where Corner defined as in OP.

+6
source

I guess it should have been

 type Corner = Corner of int*int 

In this case, this will get the first value:

 let (Corner(first,_)) = corner 
+5
source

As already mentioned, it is impossible to obtain the first discriminated case of association without naming it. But here is a fairly concise way to do this:

 Corner (1,1) |> function Corner (x,_) -> x 

In this case, the function keyword is used, which creates a function with one parameter and goes directly to the template for this parameter. Since only one case to fit it neatly fits in one line.

+3
source

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


All Articles