Shawn Zhang
Shawn Zhang

Reputation: 1884

Apply plus function in Clojure

Any idea why

(+ nil ) ;-> returns nil

(apply + nil) ;-> return 0 ?

thank you very much

enter image description here

Upvotes: 1

Views: 108

Answers (2)

akond
akond

Reputation: 16035

(apply + nil) means "use no arguments" which is equivalent to just (+).

(+)
=> 0

See source

Upvotes: 1

jas
jas

Reputation: 10865

The two cases are different.

In the case of (+ nil), the nil argument is in place of a number. In the case of (apply + nil), the nil is in place of a list of numbers.

The equivalent of

user> (+ nil)
nil

using apply would be

user> (apply + '(nil))
nil

which returns the same result.

On the other hand, by calling (apply + nil), you are calling + on an empty list, in other words calling + with no arguments, which returns 0. The following are all equivalent:

user> (+)
0    
user> (apply + nil)
0
user> (apply + '())
0

Upvotes: 6

Related Questions