共用方式為


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

更新:2010 年 5 月

將函式套用至集合的每一個項目,以透過計算建立累計值引數的執行緒。 如果輸入函數為 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
    Type: '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 |]

輸出

      

平台

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.Array 模組 (F#)

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

變更記錄

日期

History

原因

2010 年 5 月

加入程式碼範例。

資訊加強。