Search code examples
clojure

Null pointer exception when executing loop in clojure


(defn my-loop [x] 
            (cond (> x 1)
                  ((println x)
                  (my-loop (- x 1)))
            ) 
    )

;; => #'user/my-loop
user> (my-loop 10)

Why do i get a null pointer exception, when executing this function? Is this not a normal recursion?


Solution

  • You are invoking the return of (println x) with the additional layer of parentheses. println returns nil so invoking it will lead to the NullPointerException.

    To evaluate more than one form where only one is expected use the do special form, which evaluates any number of forms and returns the value of the last one:

    (defn my-loop [x]
      (cond (> x 1) (do
                      (println x)
                      (my-loop (- x 1)))))
    

    In this case, when can replace a one armed cond and do

    (defn my-loop [x]
      (when (> x 1)
        (println x)
        (my-loop (- x 1))))