Search code examples
f#sequences

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.


Solution

  • 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.