次の方法で共有


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

更新 : 2010 年 5 月

計算にアキュムレータ引数を使用しながら、コレクションの各要素に関数 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
    型: 'T list

    入力リスト。

戻り値

最終状態の値。

解説

この関数は、コンパイルされたアセンブリでは 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 7、Windows Vista SP2、Windows XP SP3、Windows XP x64 SP2、Windows Server 2008 R2、Windows Server 2008 SP2、Windows Server 2003 SP2

バージョン情報

F# ランタイム

サポート対象: 2.0、4.0

Silverlight

サポート: 3

参照

その他の技術情報

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

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

履歴の変更

日付

履歴

理由

2010 年 5 月

コード例を追加。

情報の拡充