Compartilhar via


Array.Fold < T',' estado > Função (F#)

Aplica uma função para cada elemento da coleção, um argumento acumulador por meio de computação de threading. Se a função de entrada for f e os elementos são i0...iN , em seguida, calcula f (... (f s i0)...) iN.

Caminho do namespace/módulo: 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 de elementos de entrada de dado.

  • state
    Tipo: 'State

    O estado inicial.

  • array
    Tipo: 'T []

    A matriz de entrada.

Valor de retorno

O estado final.

Comentários

Esta função é chamada de Fold em módulos (assemblies) compilados. Se você estiver acessando a função de um idioma diferente, por exemplo, F# ou através de reflexão, use esse nome.

Exemplo

O código a seguir ilustra o uso do 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 7, SP2 do Windows Vista, Windows XP SP3, Windows XP Professional x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

Informações sobre versão

O tempo de execução F#

Compatível com: 2.0, 4.0

Silverlight

Compatível com: 3

Consulte também

Referência

Módulo de Collections.Array (F#)

Microsoft.FSharp.Collections Namespace (F#)

Histórico de alterações

Date

History

Motivo

Maio de 2010

Exemplo de código adicionado.

Aprimoramento de informações.