7 people like it.

Partition a list

The snippet implements 'List.partitionWhile' which behaves as a combination of 'Seq.takeWhile' and 'Seq.skipWhile': It splits the list into a part containing elements from the beginning of a list that match a given predicate and remaining elements.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
module List = 
  /// Partition elements of a list using the specified predicate.
  /// The result is a tuple containing elements (from the beginning 
  /// of the list that satisfy the predicate) and the rest of the list.
  let partitionWhile f =
    let rec loop acc = function
      | x::xs when f x -> loop (x::acc) xs
      | xs -> List.rev acc, xs
    loop [] 

// Example use: Note that ' next' is not in the first
// part of the list, because it follows elements that do
// not start with a space!
[" foo"; " bar"; "goo"; "zoo"; " next"]
|> List.partitionWhile (fun s -> s.StartsWith(" "))
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 partitionWhile : f:('a -> bool) -> ('a list -> 'a list * 'a list)

Full name: Script.List.partitionWhile


 Partition elements of a list using the specified predicate.
 The result is a tuple containing elements (from the beginning
 of the list that satisfy the predicate) and the rest of the list.
val f : ('a -> bool)
val loop : ('a list -> 'a list -> 'a list * 'a list)
val acc : 'a list
val x : 'a
val xs : 'a list
val rev : list:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.rev
Multiple items
module List

from Script

--------------------
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 s : string
System.String.StartsWith(value: string) : bool
System.String.StartsWith(value: string, comparisonType: System.StringComparison) : bool
System.String.StartsWith(value: string, ignoreCase: bool, culture: System.Globalization.CultureInfo) : bool
Raw view Test code New version

More information

Link:http://fssnip.net/dH
Posted:11 years ago
Author:Tomas Petricek
Tags: list , sequence , seq , partition