List.fold2<'T1,'T2,'State> 函数 (F#)

将函数应用于两个集合的对应元素,并在整个计算过程中使用一个累加器参数。 集合必须具有相同的大小。 如果输入函数为 f,并且元素为 i0...iN 和 j0...jN,则计算 f (... (f s i0 j0)...) iN jN。

命名空间/模块路径: Microsoft.FSharp.Collections.List

程序集:FSharp.Core(在 FSharp.Core.dll 中)

// Signature:
List.fold2 : ('State -> 'T1 -> 'T2 -> 'State) -> 'State -> 'T1 list -> 'T2 list -> 'State

// Usage:
List.fold2 folder state list1 list2

参数

  • folder
    类型:'State -> 'T1 -> 'T2 -> 'State

    要更新为输入元素指定的状态的函数。

  • state
    类型:'State

    初始状态。

  • list1
    类型:'T1 list

    第一个输入列表。

  • list2
    类型:'T2 list

    第二个输入列表。

返回值

最终状态值。

异常

异常

Condition

ArgumentException

在输入列表的长度不同时引发。

备注

此函数在编译的程序集中名为 Fold2。 如果从 F# 以外的 .NET 语言中访问函数,或通过反射访问成员,请使用此名称。

示例

下面的代码示例演示 List.fold2 的用法。

// Use List.fold2 to perform computations over two lists (of equal size) at the same time.
// Example: Sum the greater element at each list position.
let sumGreatest list1 list2 = List.fold2 (fun acc elem1 elem2 ->
                                              acc + max elem1 elem2) 0 list1 list2

let sum = sumGreatest [1; 2; 3] [3; 2; 1]
printfn "The sum of the greater of each pair of elements in the two lists is %d." sum

Output

  

以下代码示例演示如何使用 List.fold2 来计算经过一系列交易后银行帐户的期末余额。 两个输入列表展示了交易类型(存款或取款)和交易金额。

// Discriminated union type that encodes the transaction type.
type Transaction =
    | Deposit
    | Withdrawal

let transactionTypes = [Deposit; Deposit; Withdrawal]
let transactionAmounts = [100.00; 1000.00; 95.00 ]
let initialBalance = 200.00

// Use fold2 to perform a calculation on the list to update the account balance.
let endingBalance = List.fold2 (fun acc elem1 elem2 ->
                                match elem1 with
                                | Deposit -> acc + elem2
                                | Withdrawal -> acc - elem2)
                                initialBalance
                                transactionTypes
                                transactionAmounts
printfn "%f" endingBalance

Output

  

平台

Windows 8,Windows 7,Windows server 2012中,Windows server 2008 R2

版本信息

F#核心库版本

支持:2.0,4.0,可移植

请参见

参考

Collections.List 模块 (F#)

Microsoft.FSharp.Collections 命名空间 (F#)