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

計算にアキュムレータ引数を使用しながら、2 つのコレクションの対応する要素に関数を適用します。各コレクションは同じサイズである必要があります。入力関数が 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
    型: 'T1list

    最初の入力リスト。

  • list2
    型: 'T2list

    2 番目の入力リスト。

戻り値

最終状態の値。

例外

例外

状態

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

出力

  

List.fold2 を使用して一連のトランザクションの後に銀行口座の最終的な残高を計算するコードの例を示します。2 つの入力リストは、トランザクションの種類 (預け入れと引き出し) およびトランザクションの額を表します。

// 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

出力

  

プラットフォーム

Windows 8、Windows 7、Windows Server 2012 で Windows Server 2008 R2

バージョン情報

F# コア ライブラリのバージョン

サポート: ポータブル 2.0、4.0

参照

関連項目

Collections.List モジュール (F#)

Microsoft.FSharp.Collections 名前空間 (F#)