List.choose<'T,'U> Function (F#)
Visual Studio 2012
Applies the given function f to each element x of the list. Returns the list comprised of the results for each element where the function returns Some(f(x)).
Namespace/Module Path: Microsoft.FSharp.Collections.List
Assembly: FSharp.Core (in FSharp.Core.dll)
// Signature:
List.choose : ('T -> 'U option) -> 'T list -> 'U list
// Usage:
List.choose chooser list
The following code demonstrates the use of List.choose to select capitalized words out of a list of words.
let listWords = [ "and"; "Rome"; "Bob"; "apple"; "zebra" ] let isCapitalized (string1:string) = System.Char.IsUpper string1.[0] let results = List.choose (fun elem -> match elem with | elem when isCapitalized elem -> Some(elem + "'s") | _ -> None) listWords printfn "%A" results
Output
["Rome's"; "Bob's"]