Array.fold<'T,'State> 函式 (F#)
將函式套用至集合的每一個項目,以透過計算建立累計值引數的執行緒。 如果輸入函數為 f 而且項目為 i0...iN,則會計算 f (... (f s i0)...) iN.
**命名空間/模組路徑:**Microsoft.FSharp.Collections.Array
組件:FSharp.Core (在 FSharp.Core.dll 中)
// Signature:
Array.fold : ('State -> 'T -> 'State) -> 'State -> 'T [] -> 'State
// Usage:
Array.fold folder state array
參數
folder
型別:'State -> 'T -> 'State根據指定的輸入項目更新狀態的函式。
state
型別:'State初始狀態。
array
型別:'T []輸入陣列。
傳回值
最終狀態。
備註
這個函式在已編譯的組件中名為 Fold。 如果您是透過 F# 以外的語言,或是透過反映來存取函式,請使用這個名稱。
範例
下列程式碼說明如何使用 Array.fold。
let sumArray array = Array.fold (fun acc elem -> acc + elem) 0 array
printfn "Sum of the elements of array %A is %d." [ 1 .. 3 ] (sumArray [| 1 .. 3 |])
// The following example computes the average of a array.
let averageArray array = (Array.fold (fun acc elem -> acc + float elem) 0.0 array / float array.Length)
// The following example computes the standard deviation of a array.
// 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 stdDevArray array =
let avg = averageArray array
sqrt (Array.fold (fun acc elem -> acc + (float elem - avg) ** 2.0 ) 0.0 array / float array.Length)
let testArray arrayTest =
printfn "Array %A average: %f stddev: %f" arrayTest (averageArray arrayTest) (stdDevArray arrayTest)
testArray [|1; 1; 1|]
testArray [|1; 2; 1|]
testArray [|1; 2; 3|]
// Array.fold is the same as to Array.iter when the accumulator is not used.
let printArray array = Array.fold (fun acc elem -> printfn "%A" elem) () array
printArray [|0.0; 1.0; 2.5; 5.1 |]
Output
平台
Windows 8 中, Windows 7, Windows Server 2012 上, Windows Server 2008 R2
版本資訊
F# 核心程式庫版本
支援版本:2.0, 4.0,可攜式執行檔 (PE)。