0

Could someone explain the following behaviour of the + function in Clojure (version "1.8.0")?

(+ 1)       ;; 1
(+ nil)     ;; nil
(+ 5 nil)   ;; java.lang.NullPointerException
(+ nil nil) ;; java.lang.NullPointerException
;; same behaviour with +'

Note : it doesn't throw an exception in ClojureScript :

(+ 1)       ;; 1
(+ nil)     ;; nil
(+ 5 nil)   ;; 5
(+ nil nil) ;; 0

1 Answer 1

3

look at the clojure's + source:

(defn +
  ([] 0)
  ([x] (cast Number x))
  ([x y] (. clojure.lang.Numbers (add x y)))
  ([x y & more]
     (reduce1 + (+ x y) more)))

so for the arity 1 it just casts a value to a Number. That really looks strange, that there is no check for nil here, i guess someone should submit this as a bug.

on the other hand the clojurescript's variant:

(defn ^number +
  ([] 0)
  ([x] x)
  ([x y] (cljs.core/+ x y))
  ([x y & more]
    (reduce + (cljs.core/+ x y) more)))

just returns the value (which also feels buggy, since (+ "hello") would return "hello" (well, haven't tested it, but still))

for other arities clojure uses Numbers.add (that requires numbers as params, and throws error),

while clojurescript uses this macro as far as I know:

(core/defmacro ^::ana/numeric +
  ([] 0)
  ([x] x)
  ([x y] (core/list 'js* "(~{} + ~{})" x y))
  ([x y & more] `(+ (+ ~x ~y) ~@more)))

so it's just the javascript addition, that adds nulls as zeros.

5
  • I think generally speaking Clojure adopts a ‘garbage in, garbage out’ attitude to argument validation, so I think it isn’t too surprising that + doesn’t care about the type of the arguments it’s given.
    – glts
    Feb 25, 2016 at 13:15
  • (+ "hello") ;; java.lang.ClassCastException: Cannot cast java.lang.String to java.lang.Number
    – nha
    Feb 25, 2016 at 13:20
  • well, yeah. clojure can't convert string to Number. (+ "hello") should work in clojurescript, not clojure
    – leetwinski
    Feb 25, 2016 at 13:22
  • cljs.user=> (+ "hello") "hello" cljs.user=> (+ nil "") "null" cljs.user=> (+ nil 123) 123 cljs.user=> (+ "123" nil) "123null"
    – leetwinski
    Feb 25, 2016 at 13:25
  • @glts , yeah, but since it throws an error for arities 2+ , isn't it logical to throw it for arity 1 ? imagine this: (apply + items) where items is the result of some complex function call. So when items = [nil] it will return nil, but if items = [nil, 1, 2, nil] it will obviously throw an error. And when you use the result somewhere later, i bet you would rather see the exception, instead of reviewing all your code for this weird nil to find it in this really unexpected place (well personally i don't expect nil as an addition result)
    – leetwinski
    Feb 25, 2016 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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