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

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

Den Delimarsky|Last Updated: 8/18/2017
2 Contributors

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

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

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


// Signature:
Seq.compareWith : ('T -> 'T -> int) -> seq<'T> -> seq<'T> -> int

// Usage:
Seq.compareWith comparer source1 source2


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

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

source1 Type: seq<'T>

The first input sequence.

source2 Type: seq<'T>

The second input sequence.


ArgumentNullExceptionThrown when either of the input sequences is null.

Return Value

Returns the first non-zero result from the comparison function. If the end of a sequence is reached it returns a -1 if the first sequence is shorter and a 1 if the second sequence is shorter.


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 Seq.compareWith to compare two sequences using a custom comparison function.

let sequence1 = seq { 1 .. 10 }
let sequence2 = seq { 10 .. -1 .. 1 }

// Compare two sequences element by element.
let compareSequences = Seq.compareWith (fun elem1 elem2 ->
    if elem1 > elem2 then 1
    elif elem1 < elem2 then -1
    else 0) 

let compareResult1 = compareSequences sequence1 sequence2
match compareResult1 with
| 1 -> printfn "Sequence1 is greater than sequence2."
| -1 -> printfn "Sequence1 is less than sequence2."
| 0 -> printfn "Sequence1 is equal to sequence2."
| _ -> failwith("Invalid comparison result.")


Sequence1 is less than sequence2.


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

Version Information

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

See Also

Collections.Seq Module (F#)

Microsoft.FSharp.Collections Namespace (F#)

© 2020 Microsoft