How to resolve the algorithm Sort using a custom comparator step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sort using a custom comparator step by step in the OCaml programming language

Table of Contents

Problem Statement

Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function.

Note:   Lexicographic order is case-insensitive.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sort using a custom comparator step by step in the OCaml programming language

Source code in the ocaml programming language

let mycmp s1 s2 =
  if String.length s1 <> String.length s2 then
    compare (String.length s2) (String.length s1)
  else
    String.compare (String.lowercase s1) (String.lowercase s2)


# let strings = ["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"];;
val strings : string list =
  ["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"]
# List.sort mycmp strings;;
- : string list =
["strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"]


# let strings = [|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|];;
val strings : string array =
  [|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|]
# Array.sort mycmp strings;;
- : unit = ()
# strings;;
- : string array =
[|"strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"|]


  

You may also check:How to resolve the algorithm Hello world/Newbie step by step in the Coq programming language
You may also check:How to resolve the algorithm Rename a file step by step in the Erlang programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the PHP programming language
You may also check:How to resolve the algorithm Call a foreign-language function step by step in the Perl programming language
You may also check:How to resolve the algorithm Tree traversal step by step in the J programming language