Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Seq.groupBy preserve order within groups?

Tags:

f#

sequences

I want to group a sequence and then take the first occurrence of each element in the group. When I try this

Seq.groupBy f inSeq
|> Seq.map (fun (k,s) -> (k,s|>Seq.take 1|>Seq.exactlyOne))

I find that sometimes I get a different element from s. Is this expected?

like image 906
Robert Sim Avatar asked Feb 05 '23 10:02

Robert Sim


1 Answers

Looking at the source of the groupBy implementation - here's the relevant bit:

// Build the groupings

seq |> iter (fun v ->
    let safeKey = keyf v
    let mutable prev = Unchecked.defaultof<_>
    match dict.TryGetValue (safeKey, &prev) with
    | true -> prev.Add v
    | false ->
        let prev = ResizeArray ()
        dict.[safeKey] <- prev
        prev.Add v)

It iterates through the source array and adds the values to the corresponding list for the key. The order of subsequences is directly affected by the order of the input sequence. For the same input sequence, we can expect groupBy to return identical output sequences. This is how tests are coded for groupBy.

If you're seeing variations in the resulting sequences, check the input sequence.

like image 167
Asti Avatar answered Feb 12 '23 22:02

Asti