Table of contents
TOC
Collapse the table of content
Expand the table of content

Array.compareWith<'T> Function (F#)

liboz|Last Updated: 8/18/2017

Compares two arrays using the given comparison function, element by element.

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

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

Syntax

// Signature:
Array.compareWith : ('T -> 'T -> int) -> 'T [] -> 'T [] -> int

// Usage:
Array.compareWith comparer source1 source2

Parameters

comparer Type: 'T -> 'T ->int

A function that takes an element from each of the two source arrays and returns an int. If it evaluates to a non-zero value, iteration is stopped and that value is returned.

source1 Type: 'T[]

The first input array.

source2 Type: 'T[]

The second input array.

Return Value

Returns the first non-zero result from the comparison function. If the first array has a larger element, the return value is always positive. If the second array has a larger element, the return value is always negative. When the elements are equal in the two arrays, 1 is returned if the first array is longer, 0 is returned if they are equal in length, and -1 is returned when the second array is longer.

Remarks

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

Example

The following example demonstrates the use of Array.compareWith to compare two sequences using a custom comparison function.

let array1 = [| 1 .. 3 |]
let array2 = [| 1; 2; 4; |]

// Compare two arrays element by element.
let compareArrays = Array.compareWith (fun elem1 elem2 ->
    if elem1 > elem2 then 1
    elif elem1 < elem2 then -1
    else 0) 

// Prints Array1 is less than Array2
match compareArrays array1 array2 with
| 1 -> printfn "Array1 is greater than Array2."
| -1 -> printfn "Array1 is less than Array2."
| 0 -> printfn "Array1 is equal to Array2."
| _ -> failwith("Invalid comparison result.")

let array3 = [| 1; 44; 3; |]
let array4 = [| 1; 2; |]

// Prints 42
printfn "%A" (Array.compareWith (fun elem1 elem2 -> elem1 - elem2) array3 array4)

Output

Array1 is less than Array2.
42

Platforms

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

Version Information

F# Core Library Versions

Supported in: 4.0, Portable

See Also

Collections.Array Module (F#)

Microsoft.FSharp.Collections Namespace (F#)

© 2018 Microsoft