Getting elements from n to n + x in sequence in fsharp

Simple enough, given the sequence in F #, how to get elements from index n to index n + x (inclusive)?

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

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

+4
source share
2 answers

Something like that?

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

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

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

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

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

+2
source

Source: https://habr.com/ru/post/1410936/


All Articles