3

Why does clojure allow single argument for lessthan (<) or greater than (>) operators/functions? I was wondering why it is just returning 'true' instead of forcing at least 2 arguments?

Source:

(defn >
  "Returns non-nil if nums are in monotonically decreasing order,
  otherwise false."
  {:inline (fn [x y] `(. clojure.lang.Numbers (gt ~x ~y)))
   :inline-arities #{2}
   :added "1.0"}
  ([x] true)
  ([x y] (. clojure.lang.Numbers (gt x y)))
  ([x y & more]
   (if (> x y)
     (if (next more)
       (recur y (first more) (next more))
       (> y (first more)))
     false)))
3
  • 3
    The docstring pretty much explains it already. > is not a binary operator in clojure's definition. It stands for monitonically decreasing order that does not mandate at least 2 operators.
    – Davyzhu
    Dec 3, 2015 at 6:13
  • 1
    Why does clojure allow single argument for <? Why not?
    – Mars
    Dec 3, 2015 at 7:20
  • Mathematically you need a pair to establish an ordering. So you're correct in that sense. But it's more practical to say an element of one is monotone. Dec 3, 2015 at 10:05

3 Answers 3

8

If you consider 'monotonically decreasing' to be the same as 'are there any values after the first that are greater than the previous (to which we would reject this as a monotonically decreasing series)', then a single argument to both > (and < if you say increasing/less than) fulfil this definition.

0
3

There's probably a better reason, but a simple one is this: say you got a list from someplace and you want to check that its ordered, you could simply do:

(let [ls (list-from-somplace)]
  (apply < ls)

If clojure didnt support 1 argument for < function, you would have to manually check the length of the list, making the code slightly uglier :)

Edit

mars made a good point, we still need to handle the empty list, introducing ugliness:

(let [ls (list-from-someplace)]
  (when ls (apply < ls))) 
0
2

Clojure operators that can take indefinitely many arguments often accept as few as zero or one, if it makes sense to do so. For example,

(+) ;0

As @Mars points out, it's surprising that > doesn't have a zero arity returning true. Arity one returning true is what you'd expect.

Logically, for all ... includes the case where there aren't any, in this case, neighbouring pairs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.