Share via


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 -> 'State

    A function to update the state data when given a value from an option.

  • state
    Type: 'State

    The initial state.

  • option
    Type: 'Toption

    The 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 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

Version Information

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

See Also

Reference

Core.Option Module (F#)

Microsoft.FSharp.Core Namespace (F#)