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

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

liboz|Last Updated: 8/18/2017

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

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

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


// Signature:
List.compareWith : ('T -> 'T -> int) -> 'T list -> 'T list -> int

// Usage:
List.compareWith comparer source1 source2


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

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

source1 Type: 'Tlist

The first input list.

source2 Type: 'Tlist

The second input list.

Return Value

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


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.


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

let list1 = [ 1 .. 3 ]
let list2 = [ 1; 2; 4; ]

// Compare two lists element by element.
let compareLists = List.compareWith (fun elem1 elem2 ->
    if elem1 > elem2 then 1
    elif elem1 < elem2 then -1
    else 0) 

// Prints List1 is less than List2
match compareLists list1 list2 with
| 1 -> printfn "List1 is greater than List2."
| -1 -> printfn "List1 is less than List2."
| 0 -> printfn "List1 is equal to List2."
| _ -> failwith("Invalid comparison result.")

let list3 = [ 1; 44; 3; ]
let list4 = [ 1; 2; ]

// Prints 42
printfn "%A" (List.compareWith (fun elem1 elem2 -> elem1 - elem2) list3 list4)


List1 is less than List2.


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.List Module (F#)

Microsoft.FSharp.Collections Namespace (F#)

© 2020 Microsoft