Search code examples
stringcompareocamlstring-comparison

How to compare the strings in OCaml?


I see this and I had a try in utop.

My code is just: "a" < "b"

But there is an error that: Error: This expression has type string but an expression was expected of type int.

The code and the error in prompt

Another code is:

(*
    Given a list of strings, check to see if it is ordered, i.e. whether earlier elements are less than or equal to later elements.
*)

let rec is_ordered (ls: string list): bool =
    match ls with
    | head::[] -> true
    | head1::(tail1::tail2) -> ((head1 <= tail1) && is_ordered(tail1::tail2))
    | _ -> false

And the same error.

Thanks in advance.


Solution

  • Most likely you are using modules from Jane Street. The Jane Street modules redefine the polymorphic comparison operators (like <) so that they operate only on ints.

    Here is a recent discussion: Question About OCaml Function Signatures in UTop

    If you want to keep using the Jane Street modules you can use String.compare to compare strings.