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

Wendet die angegebene Funktion auf aufeinander folgende Elemente an und gibt das erste Ergebnis zurück, bei dem die Funktion Some zurückgibt.Wenn die Funktion nicht Some für ein Element zurückgibt, wird None zurückgegeben.

Namespace/Modulpfad: 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

Parameter

  • chooser
    Typ: 'T -> 'U option

    Die Funktion, die Arrayelemente in Optionen transformiert.

  • array
    Typ: 'T[]

    Das Eingabearray.

Rückgabewert

Das erste transformierte Element, das einen Optionswert von Some besitzt, oder None, wenn die Funktion nicht Some für ein Element zurückgibt.

Hinweise

Der Name dieser Funktion in kompilierten Assemblys lautet TryPick.Verwenden Sie diesen Namen, wenn Sie in einer anderen .NET-Sprache als F# oder durch Reflektion auf die Funktion zugreifen.

Beispiel

Das folgende Beispiel veranschaulicht die Verwendung von Array.tryPick zum Suchen eines Elements, das eine Bedingung erfüllt, und zum Zurückgeben einiger zusätzlicher Daten zum Element, in diesem Fall die Quadratwurzel und die Kubikwurzel.

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

Plattformen

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

Versionsinformationen

F#-Kern-Bibliotheks-Versionen

Unterstützt in: 2,0, 4,0, portablen

Siehe auch

Referenz

Collections.Array-Modul (F#)

Microsoft.FSharp.Collections-Namespace (F#)