1 people like it.

Split a list using a separator

Split a list into chunks using the specified separator. This takes a list and returns a list of lists (chunks) that represent individual groups, separated by the given separator 'v'

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
/// Split a list into chunks using the specified separator
/// This takes a list and returns a list of lists (chunks)
/// that represent individual groups, separated by the given
/// separator 'v'
let splitBy v list =
  let yieldRevNonEmpty list = 
    if list = [] then []
    else [List.rev list]

  let rec loop groupSoFar list = seq { 
    match list with
    | [] -> yield! yieldRevNonEmpty groupSoFar
    | head::tail when head = v ->
        yield! yieldRevNonEmpty groupSoFar
        yield! loop [] tail
    | head::tail ->
        yield! loop (head::groupSoFar) tail }
  loop [] list |> List.ofSeq

// The following uses 0 as a separator
let nums = [0;1;2;0;1;3;0;4;5;0]
splitBy 0 nums
val splitBy : v:'a -> list:'a list -> 'a list list (requires equality)

Full name: Script.splitBy


 Split a list into chunks using the specified separator
 This takes a list and returns a list of lists (chunks)
 that represent individual groups, separated by the given
 separator 'v'
val v : 'a (requires equality)
Multiple items
val list : 'a list (requires equality)

--------------------
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
val yieldRevNonEmpty : ('b list -> 'b list list) (requires equality)
Multiple items
val list : 'b list (requires equality)

--------------------
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  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 rev : list:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.rev
val loop : ('a list -> 'a list -> seq<'a list>) (requires equality)
val groupSoFar : 'a list (requires equality)
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 head : 'a (requires equality)
val tail : 'a list (requires equality)
val ofSeq : source:seq<'T> -> 'T list

Full name: Microsoft.FSharp.Collections.List.ofSeq
val nums : int list

Full name: Script.nums
Raw view Test code New version

More information

Link:http://fssnip.net/nr
Posted:10 years ago
Author:Tomas Petricek
Tags: list