I'm learning Clojure and try to loop on a list using a recursive function. I manage to go all the way down the nested calls of the recursion but I have a java.lang.NullPointerException when it starts going back up. And I really cannot figure out why.
My code is very simple with some verbose prints:
(defn parse-list-metadata
[l]
(cond
(empty? l) (println "empty list should never happen")
(== (count l) 1) (str "end of recursion, l=" l)
:else ((println "going deeper, size=" (count l) ", l=" l)
(println (parse-list-metadata (rest l)))
(println "going back up")
)))
The result is:
=> (parse-list-metadata '(1 2 3 4))
going deeper, size= 4 , l= (1 2 3 4)
going deeper, size= 3 , l= (2 3 4)
going deeper, size= 2 , l= (3 4)
end of recursion, l=(4)
going back up
NullPointerException clj-l8metadata.core/parse-list-metadata (form-init896211890420472487.clj:8)
It goes all the way to a list of size 1 but after the return of the most nested call, I get the NullPointerException. I would expect some printed nil values as println return nil but I really can't understand what I am missing here.
I know there are other way to do it (doseq, recur...) but I would really like to understand what's happening here!
Do you have any idea what I'm doing wrong?
EDIT: I do know what a NullPointerException is but the Leiningen Clojure REPL is not very informative about the stack. Besides there is no variable as in Java so that it makes it quite hard to figure out how you can end up with a NullPointerException. Actually, it was due to my debugging prints that I put where Clojure expect a function. As suggested by the accepted answer, a wrapping do
made the trick. So it not a duplicate of What is a NullPointerException, and how do I fix it?