clojure 2026-11-10

I frequently find myself looking for the min or max value in a comparable collection. It seems silly to sort the entire collection when all I want is the minimum or maximum. To that end I have written transducer/collection functions that bubble up (or down) the maximum or minimum by applying min-key or max-key. Has anyone found an alternative pattern for this?

Here’s an example implementation of my approach:

(defn max-by
  ([keyfn]
   (fn
     ([] ::sentinel)
     ([max] (if (= ::sentinel max)
              (throw (IllegalArgumentException. "max-by requires a non-empty collection"))
              max))
     ([max next]
      (if (or (= ::sentinel max)
             (pos? (compare (keyfn next) (keyfn max))))
        next
        max))))
  ([keyfn coll] (transduce identity (max-by keyfn) coll)))
The error message is a bit inappropriate for both cases but good enough for my purposes.

Why not use max-key? Min and max are eager since they have to visit every item, so why the transducer?

I left out an important detail: the items I’m comparing are frequently time types and compare gives a nice semantic lift. Without that little detail, max-key would be ideal. It is frequently the case that the input needs some pre-processing and that is probably how I ended up with the transducer. What I need is a mash-up of sort-by’s facilities for comparison and “schwartzian” transform but max-key’s big O efficiency.

Ah, OK. Something like this:

=>(defn max-by-compare [a b] (if (pos? (compare a b)) a b))
#'user/max-by-compare
=>(reduce max-by-compare [1 5 3 2 6 4])
6

Once you define the reducing function, you can use it with reduce or transduce.

👍 1