How can I consider a type that is essentially a tuple like a tuple in F #

So, let's say I have a type defined like this:

type Foo = | Bar of (SomeType * SomeType * SomeType * SomeType) | ...(other defs) 

so I have a panel, which is basically a collection of 4 SomeTypes. I want to access individual members of a tuple. I tried this:

let Bar (one, two, three, four) = someBar

But when I try to refer to one or two later in a function, it says that "value or constructor is not defined." Therefore, he does not consider the appointment as expected. What is the right way to do this?

Also, if I try:

 let one,two,three,four = someBar 

He complains: it is expected that someBar will have type 'a *' b * 'c *' d, but here it has type Foo

thanks,

+4
source share
2 answers

You just need to add another set of parentheses:

 let (Bar(one,two,three,four)) = someBar 

As Stephen points out, without additional partners, the compiler treats this line of code as a definition of a new function called Bar . He is also right that pattern matching would probably be more appropriate if there were other cases in a discriminatory union.

+6
source

Considering

 type Foo = | Bar of (int * int * int * int) | Bar2 of string let x = Bar(1,2,3,4) let Bar(y1,y2,y3,y4) = x 

the last let binding is interpreted as a function, Bar : 'a * 'b * 'c * 'd -> Foo . The function name casts you away, as this is the same as your case of union, but it is the same as if you defined let some_func_takes_a_tuple_and_returns_x (y1,y2,y3,y4) = x .

I think you might have to be a little more verbose:

 let y1,y2,y3,y4 = match x with | Bar(y1,y2,y3,y4) -> y1,y2,y3,y4 

This is true, because unlike decomposition of a tuple, bindings, decomposition of Bar is dangerous here, because the match is incomplete ( x can really be some other Foo case, for example Bar2 ).

Edit

@kvb knows the secret to making this work, as you expect!

+1
source

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


All Articles