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,可移植