문제

Say I have this:

let coor = seq { ... }
// val coor : seq<int * int> = seq[(12,34); (56, 78); (90, 12); ...]

I'm trying to get the value of the first number of the second element in the sequence, in this case 56. Looking at the MSDN Collection API reference, Seq.nth 1 coor returns (56, 78), of type seq <int * int>. How do I get 56 out of it?

도움이 되었습니까?

해결책

I suggest you go through Tuple article: http://msdn.microsoft.com/en-us/library/dd233200.aspx

A couple of exceptions that might shed some light on the problem:

Function fst is used to access the first element of the tuple:

(1, 2) |> fst // returns 1

Function snd is used to access the second element

(1, 2) |> snd // returns 2

In order to extract element from wider tuples you can use following syntax:

let _,_,a,_ = (1, 2, 3, 4) // a = 3

To use it in various collections (well lambdas that are passed to collection's functions), let's start with following sequence:

let s = seq {
        for i in 1..3 do yield i,-i
    }

We end up with

seq<int * int> = seq [(1, -1); (2, -2); (3, -3)]

Let's say we want to extract only the first element (note the arguments of the lambda):

s |> Seq.map (fun (a, b) -> a)

Or even shorter:

s |> Seq.map fst

And lets finally go back to your question.

s |> Seq.nth 1 |> fst

다른 팁

It's a tuple, so you could use the function fst;

> let value = fst(Seq.nth 1 coor);;
val value : int = 56

...or access it via pattern matching;

> let value,_ = Seq.nth 1 coor;;    
val value : int = 56
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top