Say I have a sequence of 100 elements. Every 10th element I want a new list of the previous 10 elements. In this case I will end up with a list of 10 sublists.
Seq.take(10) looks promising, how can I repeatedly call it to return a list of lists?
Say I have a sequence of 100 elements. Every 10th element I want a new list of the previous 10 elements. In this case I will end up with a list of 10 sublists.
Seq.take(10) looks promising, how can I repeatedly call it to return a list of lists?
This is not bad:
Perhaps this simple pure implementation might be useful:
For example:
I found this to be easily the fastest:
i.e. window the list, zip with a list of integers, remove all the overlapping elements, and then drop the integer portion of the tuple.
now there's
Seq.chunkBySize
available:I think that the solution from Brian is probably the most reasonable simple option. A probelm with sequences is that they cannot be easily processed with the usual pattern matching (like functional lists). One option to avoid that would be to use
LazyList
from F# PowerPack.Another option is to define a computation builder for working with
IEnumerator
type. I wrote something like that recently - you can get it here. Then you can write something like:This enables using some functional patterns for list processing - most notably, you can write this as a usual recursive function (similar to the one you would write for lists/lazy lists), but it is imperative under the cover (the
let!
constructo ofiter
takes the next element and modifies the enumerator).If in doubt, use fold.
This has the advantage of being fully functional, yet touch each element of the input sequence only once(*) (as opposed to the
Seq.take
+Seq.skip
solutions proposed above).(*) Assuming O(1) Seq.append. I should certainly hope so.