Is there an idiomatic way to map two values of the same type and then compare them?


Often times, I would like to compare two objects of the same type 'a and it requires me to map these objects using a function f: 'a -> 'b.

I’ve been looking around the OCaml/Jane Street Core library and there doesn’t seem to be a short way to do this. Is there a short way to do this?

In Java, you can easily do this with the function comparing. Here is the signature of comparing:

static <T,U extends Comparable<? super U>> Comparator<T> comparing(
   Function<? super T,? extends U> keyExtractor)

You’re looking for Comparable.lift:

(** [lift cmp ~f x y] compares [x] and [y] by comparing [f x] and [f y] via [cmp]. *)
val lift : ('a -> 'a -> 'int_or_bool) -> f:('b -> 'a) -> ('b -> 'b -> 'int_or_bool)