Partager via


Array.tryPick<'T,'U>, fonction (F#)

Applique la fonction donnée à des éléments consécutifs, en retournant le premier résultat où la fonction retourne Some.Si la fonction ne retourne pas Some pour tout élément, None est retourné.

Espace de noms/Chemin du module : Microsoft.FSharp.Collections.Array

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

// Signature:
Array.tryPick : ('T -> 'U option) -> 'T [] -> 'U option

// Usage:
Array.tryPick chooser array

Paramètres

  • chooser
    Type : 'T -> 'U option

    Fonction permettant de transformer les éléments de tableau en options.

  • array
    Type : 'T[]

    Tableau d'entrée.

Valeur de retour

Le premier élément transformé ayant une valeur d'option Some ou None si la fonction ne retourne pas Some pour un élément.

Notes

Cette fonction se nomme TryPick dans les assemblys compilés.Si vous accédez à la fonction à partir d'un langage autre que F# ou par réflexion, utilisez ce nom.

Exemple

L'exemple suivant illustre l'utilisation de Array.tryPick pour tenter de localiser un élément qui remplit une condition et retourne également des informations supplémentaires à propos de l'élément ; dans ce cas, la racine carrée et la racine cubique.

let findPerfectSquareAndCube array1 =
    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 Array.tryPick testElement array1 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 |]
  
  
  
  
  

Plateformes

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

Informations de version

Versions de bibliothèque principale F#

Prise en charge dans : 2,0, 4,0, portables

Voir aussi

Référence

Collections.Array, module (F#)

Microsoft.FSharp.Collections, espace de noms (F#)