MirroredFate
MirroredFate

Reputation: 12816

Obtaining elements at n to n+x in a sequence in fsharp

Quite simply, given a sequence in F#, how does one obtain elements from index n to index n+x (inclusive)?

So, if I have a sequence like: {0; 1; 2; 3; 4; 5}, how to I get the sub-sequence from index 2 to 4? It would look like {2; 3; 4}

Any answer that uses the massive built-in F# API is preferable.

Upvotes: 4

Views: 219

Answers (2)

Massimiliano
Massimiliano

Reputation: 16980

Something like this?

let slice n x = Seq.skip n >> Seq.take (x+1)

Note that if there is not enough elements in the sequence you will get an InvalidOperationException.

Upvotes: 5

Joh
Joh

Reputation: 2380

let slice n x xs =
    xs
    |> Seq.windowed (x + 1)
    |> Seq.nth n

Note that unlike Yacoder's answer, it returns an array instead of a sequence (which may be want you want or not, depending on the situation).

I added my answer to show Seq.windowed, a very useful function IMHO. Seq.pairwise is also nice and good to know about.

Upvotes: 2

Related Questions