Skip to content

Instantly share code, notes, and snippets.

@baronfel
Created April 18, 2022 01:40
Show Gist options
  • Save baronfel/3176417948b164aa726eed8458bc4c7d to your computer and use it in GitHub Desktop.
Save baronfel/3176417948b164aa726eed8458bc4c7d to your computer and use it in GitHub Desktop.
Seq.groupWith
module Seq =
let groupWith grouper items =
seq {
let mutable currentKey = Unchecked.defaultof<'key>
let mutable currentSet = null
for item in items do
let thisKey = grouper item
if currentKey = Unchecked.defaultof<'key>
then
// new grouping
currentKey <- thisKey
currentSet <- ResizeArray()
currentSet.Add item
else
// existing grouping
if thisKey = currentKey then
currentSet.Add item
else
// beginning of new grouping
yield currentSet :> seq<_>
currentKey <- thisKey
currentSet <- ResizeArray()
currentSet.Add item
// don't forget to emit last group
yield currentSet
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment