Clojure function throws a null pointer exception

1.3k views Asked by At

I've just begun to teach myself clojure and I'm having fun. However trouble began when I began to exec this function I wrote!

It's a simple function that accepts multiple number of arguments & returns the difference between the last and the first arguments.

(defn diff-last-first 
   "gets the difference between the last & the first arguments" 
   [& args] 
   (- (get args (- (count args) 1)) (get args 0)))

I know that I can simply use the last function to get the last element of args, but I'm not able to understand why this is throwing a NullPointerException when I execute (diff-last-first 1 2 3)

3

There are 3 answers

7
deprecated On BEST ANSWER

(get (list :foo) 0) evaluates to nil.

Lists are not supposed to be accessed by index: it is a common design decision in Clojure to prevent such inefficiencies.

0
Raghu Kanchiraju On

Ok, Got it!

@vemv was right! [& args] is a list and hence (get args 0) returns nil

Whereas (defn get-l-f [args] (- (get args (- (count args) 1)) (get args 0))) works as expected as args is a vector here!

0
Daniel Neal On

If you do want to access the nth value of a list, you can use nth:

(defn diff-last-first [& args]
   (- (nth args (dec (count args)))
      (nth args 0)))

But of course, as you pointed out in your question, it is more idiomatic to use first and last:

(defn diff-last-first [& args]
  (- (last args) 
     (first args)))