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

+2 votes
in Syntax and reader by
retagged by

For comparisons (= < <= > >= ==) arity 3 and higher are much slower than doing e.g. (and (< a b) (< b c)). The arity 3 is in my research rather less common but still used in e.g. Manifold stream.clj [0] or rrb_vector rrbt.clj [1]. Arity 3 is idiomatic in places, where you compare lower and upper bound for a "variable". However, I don't think arity 4 and higher is used much in practical code. At least I haven't found any interesting instances of such a use.

An example implementation (based on the one currently in core) could be:

(defn <'
  "Returns non-nil if nums are in monotonically increasing order,
  otherwise false."
  {:inline         (fn [x y] `(. clojure.lang.Numbers (lt ~x ~y)))
   :inline-arities #{2}
   :added          "1.0"}
  ([x] true)
  ([x y] (. clojure.lang.Numbers (lt x y)))
  ([x y z] (and (<' x y) (<' y z)))
  ([x y z & more]
   (if (<' x y z)
     (if (next more)
       (recur y z (first more) (next more))
       (<' z (first more)))
     false)))

[0] https://github.com/clj-commons/manifold/blob/c3fc69066f3abba0b5ab0f4c2b1c4338bcc61d19/src/manifold/stream.clj#L978
[1] https://github.com/clojure/core.rrb-vector/blob/master/src/main/clojure/clojure/core/rrb_vector/rrbt.clj

2 Answers

0 votes
by
0 votes
ago by

Yes, I use 3-arity inequality functions with some regularity, much like PostgreSQL's BETWEEN operator, I've also seen it used by others. I think the most frequent use case for this is in tests for me personally but some of these are inside ares that can get large, so I would appreciate a performance optimization.

I would also agree that 4+ arity is exponentially rarer than 3-arity (I've never seen it in practice, but I assume there's been at least one person who has done (apply > coll) at some point to check if a collection is sorted), but I have no data on this beyond anecdotal experience.

ago by
Ah, thanks for that insight. I thought about the arity 3 as an obvious optimization and taking the list processing hit later, in fewer cases.
...