Expand Minimize

List.scan<'T,'State> Function (F#)

Applies a function to each element of the collection, threading an accumulator argument through the computation. This function takes the second argument, and applies the function to it and the first element of the list. Then, it passes this result into the function along with the second element, and so on. Finally, it returns the list of intermediate results and the final result.

Namespace/Module Path: Microsoft.FSharp.Collections.List

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
List.scan : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State list

// Usage:
List.scan folder state list

folder

Type: 'State -> 'T -> 'State

The function to update the state given the input elements.

state

Type: 'State

The initial state.

list

Type: 'T list

The input list.

The list of states.

This function is named Scan in compiled assemblies. If you are accessing the function from a .NET language other than F#, or through reflection, use this name.

The following code shows how to use List.scan.

let initialBalance = 1122.73
let transactions = [ -100.00; +450.34; -62.34; -127.00; -13.50; -12.92 ]
let balances =
    List.scan (fun balance transactionAmount -> balance + transactionAmount)
              initialBalance transactions
printfn "Initial balance:\n $%10.2f" initialBalance
printfn "Transaction   Balance" 
for i in 0 .. List.length transactions - 1 do
    printfn "$%10.2f $%10.2f" transactions.[i] balances.[i]
printfn "Final balance:\n $%10.2f" balances.[ List.length balances - 1]

Output

Initial balance:
 $   1122.73
Transaction   Balance
$   -100.00 $   1122.73
$    450.34 $   1022.73
$    -62.34 $   1473.07
$   -127.00 $   1410.73
$    -13.50 $   1283.73
$    -12.92 $   1270.23
Final balance:
 $   1257.31

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

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft