clojure - What is causing this NullPointerException? -
i'm using project euler questions me learn clojure, , i've run exception can't figure out. nillify , change-all defined @ bottom 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 nullpointerexception, , can't figure out why. part of code can see could throw such exception call nillify, doesn't seem queue ever gets down 1 element before exception thrown---and if queue become empty, that's if statement for.
any ideas?
"given vector, value, , list of indices, return vector w/everthing @ indice=value"
(defn change-all [the-vector indices val] (apply assoc the-vector (interleave indices (repeat (count indices) val))))
"given vector , val, return vector in entries indices equal multiples of val nilled, leave original untouched"
(defn nillify [coll val] (change-all coll (range (* 2 val) (inc (last coll)) val) nil))
the problem sexpr is
(inc (last coll))
you're changing contents of vector, can't use determine length anymore. instead:
(count coll)
as matter of style, use let bindings:
(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))
Comments
Post a Comment