Ian Finlayson
Ian Finlayson

Reputation: 311

NullPointerException after simple clojure program

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

Answers (1)

Arthur Ulfeldt
Arthur Ulfeldt

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 ()


Clojure does not have tail call elimination, so changing your recursive call to collatz to recur will keep it from blowing the stack on large values of n

Upvotes: 3

Related Questions