Share via


Array.fold2<'T1,'T2,'State> Function (F#)

Applies a function to pairs of elements drawn from the two collections, left-to-right, threading an accumulator argument through the computation. The two input arrays must have the same lengths, otherwise ArgumentException is raised.

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

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

// Signature:
Array.fold2 : ('State -> 'T1 -> 'T2 -> 'State) -> 'State -> 'T1 [] -> 'T2 [] -> 'State

// Usage:
Array.fold2 folder state array1 array2

Parameters

  • folder
    Type: 'State -> 'T1 -> 'T2 -> 'State

    The function to update the state given the input elements.

  • state
    Type: 'State

    The initial state.

  • array1
    Type: 'T1 []

    The first input array.

  • array2
    Type: 'T2 []

    The second input array.

Exceptions

Exception

Condition

ArgumentException

Thrown when the input arrays differ in length.

Return Value

The final state.

Remarks

This function is named Fold2 in compiled assemblies. If you are accessing the function from a language other than F#, or through reflection, use this name.

Example

The following code shows how to use Array.fold2.

// Use Array.fold2 to perform computations over two arrays (of equal size)
// at the same time.
// Example: Add the greater element at each array position.
let sumGreatest array1 array2 =
    Array.fold2 (fun acc elem1 elem2 ->
        acc + max elem1 elem2) 0 array1 array2

let sum = sumGreatest [| 1; 2; 3 |] [| 3; 2; 1 |]
printfn "The sum of the greater of each pair of elements in the two arrays is %d." sum

Output

The sum of the greater of each pair of elements in the two arrays is 8.

Platforms

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

Version Information

F# Runtime

Supported in: 2.0, 4.0

Silverlight

Supported in: 3

See Also

Reference

Collections.Array Module (F#)

Microsoft.FSharp.Collections Namespace (F#)