共用方式為


Array.tryFind<'T> 函式 (F#)

傳回第一個指定之函式會傳回 true 的項目。 如果沒有這類項目,則傳回 None。

命名空間/模組路徑: Microsoft.FSharp.Collections.Array

組件:FSharp.Core (在 FSharp.Core.dll 中)

// Signature:
Array.tryFind : ('T -> bool) -> 'T [] -> 'T option

// Usage:
Array.tryFind predicate array

參數

  • predicate
    Type: 'T -> bool

    用來測試輸入項目的函式。

  • array
    Type: 'T []

    輸入陣列。

傳回值

第一個項目滿足述詞或 None

備註

這個函式是名為 TryFind中 已編譯的組件。 如果從以.NET 語言,F # 以外,或透過反映存取函式使用這個名稱。

範例

下列範例示範使用 Array.tryFind嘗試找出陣列元素,是完美的 Cube 和 完美的平方和。

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
let lookForCubeAndSquare array1 =
    let result = Array.tryFind (fun elem -> isPerfectSquare elem && isPerfectCube elem) array1
    match result with
    | Some x -> printfn "Found an element: %d" x
    | None -> printfn "Failed to find a matching element."

lookForCubeAndSquare [| 1 .. 10 |]
lookForCubeAndSquare [| 100 .. 1000 |]
lookForCubeAndSquare [| 2 .. 50 |]
  

平台

Windows 7、Windows Vista SP2、Windows XP SP3、Windows XP x64 SP2、Windows Server 2008 R2、Windows Server 2008 SP2、Windows Server 2003 SP2

版本資訊

F# 執行階段

支援版本:2.0、4.0

Silverlight

支援版本:3

請參閱

參考

Collections.Array 模組 (F#)

Microsoft.FSharp.Collections 命名空間 (F#)