Freigeben über


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

Wendet eine Funktion auf jedes Element der Auflistung an, wobei ein Akkumulatorargument in der Berechnung mitgeführt wird. Ist die Eingabefunktion f und sind die Elemente i0...iN, wird von f (... (f s i0)...) iN. berechnet.

Namespace/Modulpfad: 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

Parameter

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

    Die Funktion, mit der der Zustand der Eingabeelemente aktualisiert wird.

  • state
    Typ: 'State

    Der Ausgangszustand.

  • array
    Typ: 'T []

    Das Eingabearray.

Rückgabewert

Der Abschlusszustand.

Hinweise

Der Name dieser Funktion in kompilierten Assemblys lautet Fold. Verwenden Sie diesen Namen, wenn Sie in einer anderen .NET-Sprache als F# oder durch Reflektion auf die Funktion zugreifen.

Beispiel

Das folgende Codebeispiel veranschaulicht die Verwendung von 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

      

Plattformen

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

Versionsinformationen

F#-Runtime

Unterstützt in: 2.0, 4.0

Silverlight

Unterstützt in: 3

Siehe auch

Weitere Ressourcen

Collections.Array-Modul (F#)

Microsoft.FSharp.Collections-Namespace (F#)

Änderungsprotokoll

Datum

Versionsgeschichte

Grund

Mai 2010

Codebeispiel hinzugefügt.

Informationsergänzung.