I have in F #, 2 sequences, each of which contains different integers, strictly in ascending order: listMaxes and numbers .
If not Seq.isEmpty numbers , then it is guaranteed that not Seq.isEmpty listMaxes and Seq.last listMaxes >= Seq.last numbers .
I would like to implement in F # a function that returns a list from a list of integers, List.length equals Seq.length listMaxes , containing numbers elements separated in lists where listMaxes elements limit each group.
For example: called with arguments
listMaxes = seq [ 25; 56; 65; 75; 88 ] numbers = seq [ 10; 11; 13; 16; 20; 25; 31; 38; 46; 55; 65; 76; 88 ]
this function should return
[ [10; 11; 13; 16; 20; 25]; [31; 38; 46; 55]; [65]; List.empty; [76; 88] ]
I can implement this function, iterating over numbers only once:
let groupByListMaxes listMaxes numbers = if Seq.isEmpty numbers then List.replicate (Seq.length listMaxes) List.empty else List.ofSeq (seq { use nbe = numbers.GetEnumerator () ignore (nbe.MoveNext ()) for lmax in listMaxes do yield List.ofSeq (seq { if nbe.Current <= lmax then yield nbe.Current while nbe.MoveNext () && nbe.Current <= lmax do yield nbe.Current }) })
But this code seems unclean, ugly, imperative and very non-F # -y.
Is there any functional / F # -diomatic way to achieve this?
source share