Partager via


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

Applique une fonction à chaque élément de la collection, en créant ainsi un thread d'un argument d'accumulation par l'intermédiaire du calcul. Si la fonction d'entrée est f et que les éléments sont i0...iN, calcule alors f (... (f s i0)...) iN..

Espace de noms/Chemin du module : 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

Paramètres

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

    Fonction permettant de mettre à jour l'état selon les éléments d'entrée.

  • state
    Type : 'State

    État initial.

  • array
    Type : 'T []

    Tableau d'entrée.

Valeur de retour

État final.

Notes

Cette fonction se nomme Fold dans les assemblys compilés. Si vous accédez à la fonction à partir d'un langage autre que F# ou par réflexion, utilisez ce nom.

Exemple

Le code suivant illustre l'utilisation 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 |]

Sortie

      

Plateformes

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

Informations de version

Runtime F#

Pris en charge dans : 2.0, 4.0

Silverlight

Prise en charge dans : 3

Voir aussi

Référence

Collections.Array, module (F#)

Microsoft.FSharp.Collections, espace de noms (F#)

Historique des modifications

Date

Historique

Motif

Mai 2010

Ajout d'un exemple de code

Améliorations apportées aux informations.