套用指定的函式傳回第一個結果,函式會傳回 的連續元素到 Some 如果函式不會傳回 Some任何項目,然後為 None傳回
命名空間/模組路徑: Microsoft.FSharp.Collections.Array
組件:FSharp.Core (在 FSharp.Core.dll 中)
// Signature:
Array.tryPick : ('T -> 'U option) -> 'T [] -> 'U option
// Usage:
Array.tryPick chooser array
參數
chooser
型別:'T -> 'U option函式,將陣列元素轉換成選項。
array
Type: 'T []輸入陣列。
傳回值
第一個有 的選項值的轉換的元素 Some,或 None如果函式不會傳回 Some的任何項目。
備註
這個函式是名為 TryPick中 已編譯的組件。 如果從一個語言,F # 以外,或透過反映存取函式使用這個名稱。
範例
下列範例示範使用 Array.tryPick嘗試找出項目滿足一個的條件,而且也傳回一些額外的資料,在這種情況下,項目相關,平方根和 Cube 的根目錄中。
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 |]
平台
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