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

将给定函数应用于连续的元素并返回第一个结果,该函数返回 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
    类型:'T []

    输入数组。

返回值

第一个转换的元素包含一个 Some 的选项值,或者如果函数不为任何元素返回Some 则为 None。

备注

此函数在编译的程序集中名为 TryPick。 如果从 F# 以外的语言中访问函数,或通过反射访问成员,请使用此名称。

示例

以下示例演示如何使用 Array.tryPick 来尝试定位满足某一条件的元素,同时返回该元素的一些其他数据,这里是指求平方根和立方根。

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 8,Windows 7,Windows server 2012中,Windows server 2008 R2

版本信息

F#核心库版本

支持:2.0,4.0,可移植

请参见

参考

Collections.Array 模块 (F#)

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