Clojure function throws null pointer exception

I just started to teach myself clojure, and I have fun. However, the problem started when I started to perform this function that I wrote!

This is a simple function that takes many arguments and returns the difference between the last and 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 args element, but I cannot understand why it throws a NullPointerException when I execute (diff-last-first 1 2 3)

+4
source share
3 answers

(get (list :foo) 0) is nil.

Lists should not be accessible by index: this is Clojure's standard design decision to prevent such inefficiencies.

+2
source

If you 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 noted in your question, it is more idiomatic to use first and last :

 (defn diff-last-first [& args] (- (last args) (first args))) 
+3
source

Well, it turned out!

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

While (defn get-lf [args] (- (get args (- (count args) 1)) (get args 0))) works as expected since args is a vector!

0
source

Source: https://habr.com/ru/post/1496797/


All Articles