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
    类型:'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])

Output

  
  

平台

Windows 8,Windows 7,Windows server 2012中,Windows server 2008 R2

版本信息

F#核心库版本

支持:2.0,4.0,可移植

请参见

参考

Collections.List 模块 (F#)

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