共用方式為


List.tryPick<'T,'U> 函式 (F#)

將指定的函式套用至後續項目,以傳回第一個讓函式針對某些值傳回 Some 的結果。 如果沒有這類項目,則傳回 None。

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

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

// Signature:
List.tryPick : ('T -> 'U option) -> 'T list -> 'U option

// Usage:
List.tryPick chooser list

參數

  • chooser
    型別:'T -> 'U option

    用來從項目產生選項的函式。

  • list
    型別:'T list

    輸入清單。

傳回值

第一個結果值,否則為 None。

備註

這個函式在已編譯的組件中名為 TryPick。 如果您是透過 F# 以外的語言,或是透過反映來存取函式,請使用這個名稱。

範例

在下列程式碼範例中,示範了如何使用 List.tryPick

let findPerfectSquareAndCube list1 =
    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 List.tryPick testElement list1 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 ]

Output

  
  
  
  
  

平台

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

版本資訊

F# 核心程式庫版本

支援版本:2.0, 4.0,可攜式執行檔 (PE)。

請參閱

參考

Collections.List 模組 (F#)

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