共用方式為


List.fold<'T,'State> 函式 (F#)

更新:2010 年 5 月

適用於函式 f到各個項目的集合,執行緒累加引數到 計算中。 fold函數使用第二個] 引數,然後套用函式 f和第一的項目 清單中。 然後,摘要此結果到該函式 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
    Type: '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#)

變更記錄

日期

History

原因

2010 年 5 月

加入程式碼範例。

資訊加強。