Поделиться через


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

Parameters

  • 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.

Return Value

The list of states.

Remarks

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.

Example

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

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

See Also

Reference

Collections.List Module (F#)

Microsoft.FSharp.Collections Namespace (F#)