Reputation: 311
I am working on learning clojure, and have run into a NullPointerException that seems to have nothing to do with my code. The program runs to completion before producing the error. The code:
; solves the collatz conjecture
; return one step in the sequence
(defn collatz-step [n]
(if (= (rem n 2) 0)
(/ n 2)
(+ 1 (* 3 n))))
; recurse over all numbers
(defn collatz [n]
(if (= n 1)
(println "All done!")
((println (format "N = %d" n))
(collatz (collatz-step n)))))
; get input and run it
(println "Enter a positive number:")
(collatz (read-string (read-line)))
Is there something I'm missing?
Upvotes: 2
Views: 169
Reputation: 91554
when this line runs:
((println (format "N = %d" n))
(collatz (collatz-step n)))
the println and colatz will finish leving the form like this:
(return-value-of-println return-value-of-collatz)
println returns nil yielding:
(nil return-value-of-collatz)
which is a function call to the function nil resulting in an NPE
take out the extra ()
collatz
to recur
will keep it from blowing the stack on large values of n
Upvotes: 3