Funzione Array.fold<'T,'State> (F#)

Applica una funzione a ogni elemento della raccolta, eseguendo il threading di un argomento di accumulatore attraverso il calcolo.Se la funzione di input è f e gli elementi sono i0...iN, calcola f (... (f s i0)...) iN..

Percorso di spazio dei nomi/modulo: Microsoft.FSharp.Collections.Array

Assembly: FSharp.Core (in FSharp.Core.dll)

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

// Usage:
Array.fold folder state array

Parametri

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

    Funzione da utilizzare per aggiornare lo stato in base agli elementi di input.

  • state
    Tipo: 'State

    Stato iniziale.

  • array
    Tipo: 'T[]

    Matrice di input.

Valore restituito

Stato finale.

Note

Questa funzione è denominata Fold negli assembly compilati.Utilizzare questo nome se si accede alla funzione da un linguaggio diverso da F# o tramite reflection.

Esempio

Nel codice riportato di seguito viene illustrato l'utilizzo di 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

  
  

Piattaforme

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

Informazioni sulla versione

Versioni della libreria di base F#

Supportato in: 2,0, 4,0, portabile

Vedere anche

Riferimenti

Modulo Collections.Array (F#)

Spazio dei nomi Microsoft.FSharp.Collections (F#)