共用方式為


Option.fold<'T,'State> 函式 (F#)

評估與選項相等的 List.fold

命名空間/模組路徑:Microsoft.FSharp.Core.Option

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

// Signature:
fold : ('State -> 'T -> 'State) -> 'State -> 'T option -> 'State

// Usage:
fold folder state option

參數

  • folder
    型別:'State -> 'T -> 'State

    從選項指定值時更新狀態資料的函式。

  • state
    型別:'State

    初始狀態。

  • option
    型別:'T option

    輸入選項。

傳回值

如果選項是 None 則為原始狀態,否則會傳回資料夾的已更新狀態和選項值。

備註

運算式 fold f s inp 會評估為 match inp with None -> s | Some x -> f s x。

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

範例

下列程式碼說明如何使用 Option.fold

let consOption list opt =
    Option.fold (fun state value -> value :: state) list opt
printfn "%A" <| consOption [1 .. 10] None
printfn "%A" <| consOption [1 .. 10] (Some(0))

// Read input from the console, and if the input parses as
// an integer, cons to the list.
let readNumber () =
    let line = System.Console.ReadLine()
    let (success, value) = System.Int32.TryParse(line)
    if success then Some(value) else None
let mutable list1 = []
let mutable count = 0
while count < 5 do
    printfn "Enter a number: "
    list1 <- consOption list1 (readNumber())
    printfn "New list: %A" <| list1
    count <- count + 1

Output

  

平台

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

版本資訊

F# 核心程式庫版本

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

請參閱

參考

Core.Option 模組 (F#)

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