Share via


Funzione List.tryPick<'T,'U> (F#)

Applica la funzione specificata a elementi consecutivi, restituendo il primo risultato in cui la funzione restituisce Some per alcuni valori.Se l'elemento non esiste, restituisce None.

Percorso di spazio dei nomi/modulo: Microsoft.FSharp.Collections.List

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
List.tryPick : ('T -> 'U option) -> 'T list -> 'U option

// Usage:
List.tryPick chooser list

Parametri

  • chooser
    Tipo: 'T -> 'Uoption

    Funzione da utilizzare per generare opzioni dagli elementi.

  • list
    Tipo: 'Tlist

    Elenco di input.

Valore restituito

Primo valore risultante o None.

Note

Questa funzione è denominata TryPick negli assembly compilati.Utilizzare questo nome se si accede alla funzione da un linguaggio diverso da F# o tramite reflection.

Esempio

Nell'esempio di codice riportato di seguito viene illustrato come utilizzare la classe List.tryPick.

let findPerfectSquareAndCube list1 =
    let delta = 1.0e-10
    let isPerfectSquare (x:int) =
        let y = sqrt (float x)
        abs(y - round y) < delta
    let isPerfectCube (x:int) =
        let y = System.Math.Pow(float x, 1.0/3.0)
        abs(y - round y) < delta
    // intFunction : (float -> float) -> int -> int
    // Allows the use of a floating point function with integers.
    let intFunction function1 number = int (round (function1 (float number)))
    let cubeRoot x = System.Math.Pow(x, 1.0/3.0)
    // testElement: int -> (int * int * int) option
    // Test an element to see whether it is a perfect square and a perfect
    // cube, and, if so, return the element, square root, and cube root
    // as an option value. Otherwise, return None.
    let testElement elem = 
        if isPerfectSquare elem && isPerfectCube elem then
            Some(elem, intFunction sqrt elem, intFunction cubeRoot elem)
        else None
    match List.tryPick testElement list1 with
    | Some (n, sqrt, cuberoot) ->
        printfn "Found an element %d with square root %d and cube root %d." n sqrt cuberoot
    | None ->
        printfn "Did not find an element that is both a perfect square and a perfect cube."

findPerfectSquareAndCube [ 1 .. 10 ]
findPerfectSquareAndCube [ 2 .. 100 ]
findPerfectSquareAndCube [ 100 .. 1000 ]
findPerfectSquareAndCube [ 1000 .. 10000 ]
findPerfectSquareAndCube [ 2 .. 50 ]

Output

  
  
  
  
  

Piattaforme

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

Informazioni sulla versione

Versioni della libreria di base F#

Supportato in: 2,0, 4,0, portabile

Vedere anche

Riferimenti

Modulo Collections.List (F#)

Spazio dei nomi Microsoft.FSharp.Collections (F#)