0 people like it.

List.groupWhile function

This snippet declares a function that operates on lists that groups elements of a sequence while the predicate holds. A new group is started for an element when the predicate no longer holds. The predicate is passed the current element and the previous element. This implementation is likely not very efficient.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
module List =
    let groupWhile<'a> (predicate : 'a -> 'a -> bool) =
        List.scan (fun state item ->
            let prevHead = state |> List.tryHead |> Option.bind List.tryHead
            if prevHead |> Option.map (predicate item) |> Option.defaultValue false
            then (item :: List.head state) :: (List.tail state)
            else [item] :: state) []
        >> List.last
        >> List.map List.rev
        >> List.rev
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member GetSlice : startIndex:int option * endIndex:int option -> 'T list
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val groupWhile : predicate:('a -> 'a -> bool) -> ('a list -> 'a list list)

Full name: Script.List.groupWhile
val predicate : ('a -> 'a -> bool)
type bool = System.Boolean

Full name: Microsoft.FSharp.Core.bool
val scan : folder:('State -> 'T -> 'State) -> state:'State -> list:'T list -> 'State list

Full name: Microsoft.FSharp.Collections.List.scan
val state : 'a list list
val item : 'a
val prevHead : 'a option
val tryHead : list:'T list -> 'T option

Full name: Microsoft.FSharp.Collections.List.tryHead
module Option

from Microsoft.FSharp.Core
val bind : binder:('T -> 'U option) -> option:'T option -> 'U option

Full name: Microsoft.FSharp.Core.Option.bind
val map : mapping:('T -> 'U) -> option:'T option -> 'U option

Full name: Microsoft.FSharp.Core.Option.map
val head : list:'T list -> 'T

Full name: Microsoft.FSharp.Collections.List.head
val tail : list:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.tail
val last : list:'T list -> 'T

Full name: Microsoft.FSharp.Collections.List.last
val map : mapping:('T -> 'U) -> list:'T list -> 'U list

Full name: Microsoft.FSharp.Collections.List.map
val rev : list:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.rev
Raw view Test code New version

More information

Link:http://fssnip.net/7VX
Posted:5 years ago
Author:Matthew Rodatus
Tags: grouping , list