Share via


Array.fold<'T,'State> (Función de F#)

Aplica una función a cada elemento de la colección y subprocesa un argumento acumulador durante el cálculo. Si la función de entrada es f y los elementos son i0...iN, calcula f (... (f s i0)...) iN..

Espacio de nombres/Ruta de acceso del módulo: Microsoft.FSharp.Collections.Array

Ensamblado: FSharp.Core (en FSharp.Core.dll)

// Signature:
Array.fold : ('State -> 'T -> 'State) -> 'State -> 'T [] -> 'State

// Usage:
Array.fold folder state array

Parámetros

  • folder
    Tipo: 'State -> 'T -> 'State

    Función que se va a usar para actualizar el estado asignado a los elementos de entrada.

  • state
    Tipo: 'State

    Estado inicial.

  • array
    Tipo: 'T []

    Matriz de entrada.

Valor devuelto

Estado final.

Comentarios

Esta función se denomina Fold en los ensamblados compilados. Si obtiene acceso a la función desde un lenguaje distinto de F# o mediante reflexión, use este nombre.

Ejemplo

En el código siguiente, se muestra el uso de 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

      

Plataformas

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

Información de versiones

Runtime de F#

Se admite en las versiones: 2.0, 4.0

Silverlight

Se admite en la versión: 3

Vea también

Referencia

Collections.Array (Módulo de F#)

Microsoft.FSharp.Collections (Espacio de nombres de F#)

Historial de cambios

Fecha

Historial

Motivo

Mayo de 2010

Se ha agregado un ejemplo de código.

Mejora de la información.