Option.fold<'T,'State> Function (F#)
Evaluates the equivalent of List.fold for an option.
Namespace/Module Path: Microsoft.FSharp.Core.Option
Assembly: FSharp.Core (in FSharp.Core.dll)
// Signature:
fold : ('State -> 'T -> 'State) -> 'State -> 'T option -> 'State
// Usage:
fold folder state option
Parameters
folder
Type: 'State -> 'T -> 'StateA function to update the state data when given a value from an option.
state
Type: 'StateThe initial state.
option
Type: 'T optionThe input option.
Return Value
The original state if the option is None, otherwise it returns the updated state with the folder and the option value.
Remarks
The expression fold f s inp evaluates to match inp with None -> s | Some x -> f s x.
This function is named Fold in compiled assemblies. If you are accessing the function from a language other than F#, or through reflection, use this name.
Example
The following code illustrates the use of 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
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10] [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10] Enter a number: New list: [] Enter a number: 10 New list: [10] Enter a number: 1 New list: [1; 10] Enter a number: abc New list: [1; 10] Enter a number: 9 New list: [9; 1; 10]
Platforms
Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2
Version Information
F# Runtime
Supported in: 2.0, 4.0
Silverlight
Supported in: 3