List.fold<'T,'State> 関数 (F#)

計算にアキュムレータ引数を使用しながら、コレクションの各要素に関数 f を適用します。fold 関数は、まず 2 番目の引数を受け取り、その引数とリストの最初の要素に関数 f を適用します。次に、この結果を 2 番目の要素と共に関数 f に渡します。それ以降も同様に繰り返します。最後に、最終結果を返します。入力関数が f で、要素が i0...iN の場合は、f (... (f s i0) i1 ...) iN を計算します。

名前空間/モジュール パス: Microsoft.FSharp.Collections.List

アセンブリ: FSharp.Core (FSharp.Core.dll 内)

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

// Usage:
List.fold folder state list

パラメーター

  • folder
    型: 'State -> 'T -> 'State

    入力要素を受け取って状態を更新する関数。

  • state
    型: 'State

    初期状態です。

  • list
    型: 'Tlist

    入力リスト。

戻り値

最終状態の値。

解説

この関数は、コンパイルされたアセンブリでは Fold という名前です。F# 以外の言語から、またはリフレクションを使用してこの関数にアクセスする場合は、この名前を使用します。

使用例

次の例は、List.fold の使い方を示しています。

let data = [("Cats",4);
            ("Dogs",5);
            ("Mice",3);
            ("Elephants",2)]
let count = List.fold (fun acc (nm,x) -> acc+x) 0 data
printfn "Total number of animals: %d" count
  

List.fold のその他の使い方を次のコード例に示します。以下に実装されている機能を既にカプセル化しているライブラリ関数が存在します。たとえば、List.sum を使用して、リストのすべての要素を合計できます。

let sumList list = List.fold (fun acc elem -> acc + elem) 0 list
printfn "Sum of the elements of list %A is %d." [ 1 .. 3 ] (sumList [ 1 .. 3 ])

// The following example computes the average of a list.
let averageList list = (List.fold (fun acc elem -> acc + float elem) 0.0 list / float list.Length)

// The following example computes the standard deviation of a list.
// The standard deviation is computed by taking the square root of the
// sum of the variances, which are the differences between each value
// and the average.
let stdDevList list =
    let avg = averageList list
    sqrt (List.fold (fun acc elem -> acc + (float elem - avg) ** 2.0 ) 0.0 list / float list.Length)

let testList listTest =
    printfn "List %A average: %f stddev: %f" listTest (averageList listTest) (stdDevList listTest)

testList [1; 1; 1]
testList [1; 2; 1]
testList [1; 2; 3]

// List.fold is the same as to List.iter when the accumulator is not used.
let printList list = List.fold (fun acc elem -> printfn "%A" elem) () list
printList [0.0; 1.0; 2.5; 5.1 ]

// The following example uses List.fold to reverse a list.
// The accumulator starts out as the empty list, and the function uses the cons operator
// to add each successive element to the head of the accumulator list, resulting in a
// reversed form of the list.
let reverseList list = List.fold (fun acc elem -> elem::acc) [] list
printfn "%A" (reverseList [1 .. 10])

出力

  
  

プラットフォーム

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

バージョン情報

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

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

参照

関連項目

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

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