3 people like it.

Seq group continuous matching elements

Seq group continuous matching elements [1;1;1;2;2;2] will become [ [1;1;1] ; [2;2;2] ]

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
module Seq =
    
    let group (p:'a -> 'a -> bool) (s:'a seq) = 
        if s |> Seq.isEmpty then seq []
        else
            let h = s |> Seq.head
            let state = ( (h,seq [h]) , Seq.empty)
            let ((a,b),c) = 
                s |> Seq.skip 1 
                |> Seq.fold (fun ( (a,b),c) i -> 
                                if p a i then ( (a,seq { yield! b; yield i}) ,c)
                                else ( (i, seq {yield i}), seq {yield! c; yield b}) ) 
                                state 
            seq { yield! c; yield b}

[1;2;3;4;4;4;4] |> Seq.group (=) |> printfn "%A"
module Seq

from Microsoft.FSharp.Collections
val group : p:('a -> 'a -> bool) -> s:seq<'a> -> seq<seq<'a>>

Full name: Script.Seq.group
val p : ('a -> 'a -> bool)
type bool = System.Boolean

Full name: Microsoft.FSharp.Core.bool
val s : 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 isEmpty : source:seq<'T> -> bool

Full name: Microsoft.FSharp.Collections.Seq.isEmpty
val h : 'a
val head : source:seq<'T> -> 'T

Full name: Microsoft.FSharp.Collections.Seq.head
val state : ('a * seq<'a>) * seq<seq<'a>>
val empty<'T> : seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.empty
val a : 'a
val b : seq<'a>
val c : seq<seq<'a>>
val skip : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.skip
val fold : folder:('State -> 'T -> 'State) -> state:'State -> source:seq<'T> -> 'State

Full name: Microsoft.FSharp.Collections.Seq.fold
val i : 'a
Multiple items
module Seq

from Script

--------------------
module Seq

from Microsoft.FSharp.Collections
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn

More information

Link:http://fssnip.net/6t
Posted:13 years ago
Author:Ankur Dhama
Tags: sequence