Welcome! Please see the About page for a little more info on how this works.

+3 votes
in Clojure by
retagged by

The clojuredoc for sort says:
comparator MUST implement java.util.Comparator.
However, this does not seem to be the case. The function provided as 1nd argument to 2-ary sort may return explicitly true or false; it need not implement java.util.Comparator.

It would be nice if the clojuredoc were updated to reflect this important feature.

There is another document https://clojure.org/guides/comparators which explains in greater detail. But the existence of that document does not obviate (in my opinion) the short doc from being correct even if incomplete.

1 Answer

+1 vote
by

It is not wrong. Clojure functions are instances of java.util.Comparator. The link provided by Dave in a comment gives more details.

by
Even so, it seems like this could be improved? The docstring doesn't point to that guide. The guide itself doesn't say anything about all Clojure functions implementing their own compare.
by
I agree that the docstring of `sort` and `sort-by` should point to the guide.

The guide itself indeed doesn't mention that impl detail explicitly, but I don't see how else it can be interpreted given that it explicitly says that you "can see this by calling the compare method of any Clojure function".

And this particular detail is mentioned explicitly at https://clojure.org/reference/special_forms#fn, which is mentioned by the docstring of `fn`.
by
fair point about the impl detail text in the guide. agreed that docstring pointing to the guide should probably be the goal.
by
edited by
In seems the documentation should provide the user with not only true information but useful information.  The reader wants to know how to construct a valid compare function.  I.e., it should be EITHER 1) a binary function that returns explicitly `false` if two given elements are out of order, `false` if the values are equal, and explicitly `true` (as opposed to any truthy value)
otherwise OR 2) a binary function that returns a negative, zero, or positive integer indicating the relative order of its arguments.  for more details of corner cases, see ...
by
I think mentioning in the sort docstring that fn implements Comparator would solve this issue.
...