2

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Oh man, thank you so much. That makes total sense. I thought that to group multiple statements, I had to list them in parenthesis. Now I learned about the (do ) form which solves that problem. I was banging my head over this for so long, thanks again!
functions add the do automatically, so in this case you dont need it. The last form in a function is the return value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.