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

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

Den Delimarsky|Last Updated: 8/18/2017
1 Contributor

Sorts the elements of an array, using the given comparison function as the order, returning a new array.

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

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


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

// Usage:
Array.sortWith comparer array


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

The function to compare pairs of array elements.

array Type: 'T[]

The input array.

Return Value

The sorted array.


This is not a stable sort, that is, the original order of equal elements might not be preserved. For a stable sort, consider using Seq.sort.

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


The following code shows the use of Array.sortWith.

open System

let array1 = [| "<>"; "&"; "&&"; "&&&"; "<"; ">"; "|"; "||"; "|||" |]
printfn "Before sorting: "
array1 |> printfn "%A"
let sortFunction (string1:string) (string2:string) =
    if (string1.Length > string2.Length) then
    else if (string1.Length < string2.Length) then
        String.Compare(string1, string2)

Array.sortWith sortFunction array1
|> printfn "After sorting: \n%A"


Before sorting:
[|"&lt;&gt;"; "&amp;"; "&amp;&amp;"; "&amp;&amp;&amp;"; "&lt;"; "&gt;"; "|"; "||"; "|||"|]
After sorting:
[|"&amp;"; "|"; "&lt;"; "&gt;"; "&amp;&amp;"; "||"; "&lt;&gt;"; "&amp;&amp;&amp;"; "|||"|]


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

Microsoft.FSharp.Collections Namespace (F#)

© 2020 Microsoft