F # Sequences - how to return multiple lines

let x = [for p in db.ParamsActXes do if p.NumGroupPar = grp then yield p.Num, p.Name] 

Here is my sequence, but the problem is that it returns a list of tuples, I cannot access one element of the tuple, for example

 let str = "hello" + x.[1] 

and this is a problem.

How can I implement this functionality?

+1
source share
4 answers

To access the second element of a 2-tuple, you can use snd or pattern matching. Therefore, if tup is a 2-tuple, where the second tup element is a string, you can either do:

 let str = "hello" + snd tup 

or

 let (a,b) = tup let st = "hello" + b 

Note that snd only works with 2 tuples, and not with more than two elements.

+4
source

To give you another alternative solution, you can simply create a filtered sequence containing the values โ€‹โ€‹of the original type by writing yield p :

 let x = [ for p in db.ParamsActXes do if p.NumGroupPar = grp then yield p ] 

And then just select the property you want:

 let str = "hello" + x.[1].Name 

This is probably a good idea if you are returning only a few properties of the p value. The only reason for getting tuples would be to hide something from the rest of the code or create a sequence that matches some function that you use later.

(Also, I would avoid indexing into lists using x.[i] because it is inefficient, but maybe it's just an illustration in the example you posted. Use an array if you need index-based access, T25> )

+3
source

Just to add one more feature, if you are using the .NET 4.0 F # 2.0 assembly, you can debug at runtime from the F # tuple to the .NET 4.0 System.Tuple platform, and then use the ItemX properties of the .NET 4.0 tuples to access to the tuple element you need,

 let x = (1, 1.2, "hello") let y = ((box x) :?> System.Tuple<int, float, string>);; y.Item3 //returns "hello" 

However, I would never use this, instead chose the choice of matching the pattern. (also, I read places that the F # compiler cannot always choose to represent its tuples as tuples of .NET 4.0, so there may be a chance that the cast will fail).

After reading your comments in some other answers, I'm not sure why the template solution doesn't work for you. Perhaps you want to access the tuple element in a specific place inside the expression? If so, the previous one will certainly work:

 let str = "hello" + ((box x.[1]) :?> System.Tuple<int,string>).Item2 //though might as well use snd and fst for length 2 F# tuples 

but you can achieve the same goals using the pattern matching technique (again, considering that this is even what you need):

 let str = "hello" + (let (_,name) = x.[1] in name) 
+2
source

you can access individual tuples from the list of tuples using List.nth.

 let first, second = List.nth x 0 

the first and second are a separate element of the tuple.

+1
source

All Articles