Created
April 18, 2022 01:40
-
-
Save baronfel/3176417948b164aa726eed8458bc4c7d to your computer and use it in GitHub Desktop.
Seq.groupWith
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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