共用方式為


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

將函式 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
    型別:'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])

Output

  
  

平台

Windows 8 中, Windows 7, Windows Server 2012 上, Windows Server 2008 R2

版本資訊

F# 核心程式庫版本

支援版本:2.0, 4.0,可攜式執行檔 (PE)。

請參閱

參考

Collections.List 模組 (F#)

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