Newbie: how to sort a list using Base?

Without using base, I was able to just do this:

List.sort compare my_list

But after putting open Base on top of my file, the compiler is slapping me on the wrist. I found this answer (here in this forum) but I’d like to avoid using the polymorphic compare whose usage is now discouraged.

So, how do I sort, say, a char list?

You should use the comparison function for the element type. For example:

utop # List.sort ['d'; 'b'; 'c'] ~compare:Char.compare;;
- : char list = ['b'; 'c'; 'd']

For polymorphic types, the idiom in Base is to have a compare function that takes another compare function:

utop # List.sort [Some 3; None; Some 2] ~compare:(Option.compare Int.compare);;
- : int option list = [None; Some 2; Some 3]

For convenience, you can also use something like ppx_compare, which can generate the correct expression to build the comparison function based on the type you give:

utop # List.sort [Some 3; None; Some 2] ~compare:[%compare: int option];;
- : int option list = [None; Some 2; Some 3]
2 Likes

Thank you. I am a total newbie but I believe the docs could benefit from a few examples. It’s kind of hard to stumble like I do and having to discover so much either by reading lengthy articles or asking on forums.

Thanks for being here. :slight_smile:


EDIT: I’d expect this:

List.sort [Some 3; None; Some 2] ~compare:(Option.compare Int.compare)

to have been aliased to something like this:

OptionList.sort [Some 3; None; Some 2]

OCaml is famous for being very terse, so this is kind of surprising to me.

1 Like

You would still need to have an IntegerOptionList.sort (because Base tries to avoid polymorphic compare) and then a FloatOptionList.sort and a IntegerResult.sort etc at which point you would have a lot of modules and it is easier to just compose the exact comparison function you want to have.

I don’t think OCaml is particularly terse, to me it seems on the rather verbose side of functional languages when compared to e.g. Clojure (which doesn’t have types or the module language), Scala (which has a lot more syntactic sugar) or Haskell (which has custom operators for nearly every possible thing).

1 Like