Compartilhar via


Função Array.fold<'T,'State> (F#)

Aplica uma função para cada elemento da coleção, rosqueando um argumento de acumulador com a computação. Se a função de entrada é f e os elementos são i0...iN então computador cria um f (... (f s i0)...) iN.

Namespace/Module Path: Microsoft.FSharp.Collections.Array

Assembly: FSharp.Core (em 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

    A função para atualizar o estado determinado os elementos de entrada.

  • state
    Tipo: 'State

    o estado inicial.

  • array
    Tipo: 'T[]

    A matriz de entrada.

Valor de retorno

o estado final.

Comentários

Essa função é chamada Fold em assemblies compilados. Se você está acessando a função de um idioma diferente F#, ou com a reflexão, use este nome.

Exemplo

O código a seguir ilustra o 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 |]

Saída

  
  

Plataformas

O windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

Informações de Versão

Versões da biblioteca principal de F#

Suportado em: 2,0, 4,0, portáteis

Consulte também

Referência

Módulo Collections.Array (F#)

Namespace Microsoft.FSharp.Collections (F#)