Partager via


List.choose<'T,'U> Function (F#)

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

Parameters

  • chooser
    Type: 'T -> 'Uoption

    The function to generate options from the elements.

  • list
    Type: 'Tlist

    The input list.

Return Value

The list comprising the values selected from the chooser function.

Remarks

This function is named Choose in compiled assemblies. If you are accessing the function from a language other than F#, or through reflection, use this name.

Example

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"]

Platforms

Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

Version Information

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

See Also

Reference

Collections.List Module (F#)

Microsoft.FSharp.Collections Namespace (F#)