5 people like it.

groupAdjacent

A variation of another snippet "Seq.groupWhen". This one groups adjacent elements based on a predicate that accepts two arguments - the previous and current elements

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
module Seq =
  let groupAdjacent f (input:seq<_>) = seq {
    use en = input.GetEnumerator()
    let running = ref true
    let rec group() = 
      [ let prev = en.Current
        if en.MoveNext() then
          if (f (prev,en.Current)) then  yield prev; yield! group() else yield prev
        else
            yield prev 
            running := false ]
    if en.MoveNext() then
      while running.Value do
        yield group() |> Seq.ofList }
(*
["a"; "a"; "a"; "b"; "c"; "c"] |> Seq.groupAdjacent (fun (a,b)->a=b)
val it : seq<seq<string>> = seq [["a"; "a"; "a"]; ["b"]; ["c"; "c"]]
*)
module Seq

from Microsoft.FSharp.Collections
val groupAdjacent : f:('a * 'a -> bool) -> input:seq<'a> -> seq<seq<'a>>

Full name: Script.Seq.groupAdjacent
val f : ('a * 'a -> bool)
val input : seq<'a>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val en : System.Collections.Generic.IEnumerator<'a>
System.Collections.Generic.IEnumerable.GetEnumerator() : System.Collections.Generic.IEnumerator<'a>
val running : bool ref
Multiple items
val ref : value:'T -> 'T ref

Full name: Microsoft.FSharp.Core.Operators.ref

--------------------
type 'T ref = Ref<'T>

Full name: Microsoft.FSharp.Core.ref<_>
val group : (unit -> 'a list)
val prev : 'a
property System.Collections.Generic.IEnumerator.Current: 'a
System.Collections.IEnumerator.MoveNext() : bool
property Ref.Value: bool
val ofList : source:'T list -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.ofList

More information

Link:http://fssnip.net/mI
Posted:3 years ago
Author:Faisal Waris
Tags: seq , sequence