Does Seq.groupBy keep order within groups?

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 another element from s. Is this expected?

+4
source share
2 answers

Looking at the source of implementationgroupBy - here is the corresponding 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)

. . , groupBy . , groupBy.

, .

+4

, . (seq) pure. , , . Seq.take 1, .

, , :

open System

let r = Random ()
let s = seq { yield r.Next(0, 9) }

Seq.take 1, :

> s |> Seq.take 1;;
val it : seq<int> = seq [4]
> s |> Seq.take 1;;
val it : seq<int> = seq [1]

Seq.head :

> s |> Seq.head;;
val it : int = 2
> s |> Seq.head;;
val it : int = 6

, List.

+4

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


All Articles