What causes this NullPointerException?

I use Project Euler questions to help me learn clojure, and I came across an exception that I cannot understand. nillify and change-all are defined at the bottom for reference.

(loop [the-vector (vec (range 100)) queue (list 2 3 5 7)] (if queue (recur (nillify the-vector (first queue)) (next queue)) the-vector)) 

This throws a NullPointerException, and I can't figure out why. The only part of the code that I can see that can throw such an exception is a call to nillify, but it does not seem that the queue reaches one element before the exception is thrown --- and even if the queue was empty, for which the if statement is used.

Any ideas?

"given the vector, value, and list of indices, return the vector w / everthing @indice = value"

 (defn change-all [the-vector indices val] (apply assoc the-vector (interleave indices (repeat (count indices) val)))) 

"specified by the vector and val, return a vector in which all records with indices equal to a multiple of val are filled, but leave the original untouched"

 (defn nillify [coll val] (change-all coll (range (* 2 val) (inc (last coll)) val) nil)) 
+4
source share
1 answer

Sexpr problem

 (inc (last coll)) 

You change the contents of the vector, you cannot use it to determine the length. Instead of this:

 (count coll) 

Use let bindings as a style:

 (defn change-all [the-vector indices val] (let [c (count indices) s (interleave indices (repeat c val))] (apply assoc the-vector s))) (defn nillify [coll val] (let [c (count coll) r (range (* 2 val) c val)] (change-all coll r nil))) (loop [the-vector (vec (range 100)) [f & r] '(2 3 5 7)] (if r (recur (nillify the-vector f) r) the-vector)) 
+5
source

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


All Articles