i working on learning clojure, , have run nullpointerexception seems have nothing code. program runs completion before producing error. code:
; solves collatz conjecture ; return 1 step in sequence (defn collatz-step [n] (if (= (rem n 2) 0) (/ n 2) (+ 1 (* 3 n)))) ; recurse on numbers (defn collatz [n] (if (= n 1) (println "all done!") ((println (format "n = %d" n)) (collatz (collatz-step n))))) ; input , run (println "enter positive number:") (collatz (read-string (read-line)))
is there i'm missing?
when line runs:
((println (format "n = %d" n)) (collatz (collatz-step n)))
the println , colatz finish leving form this:
(return-value-of-println return-value-of-collatz)
println returns nil yielding:
(nil return-value-of-collatz)
which function call function nil resulting in npe
take out ()
clojure not have tail call elimination, changing recursive call
collatz
recur
keep blowing stack on large values of n
Comments
Post a Comment