4

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.

MirroredFate
  • 12,396
  • 14
  • 68
  • 100

2 Answers2

5

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.

Massimiliano
  • 16,770
  • 10
  • 69
  • 112
2
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.

Joh
  • 2,380
  • 20
  • 31