1

I've tried several versions of this Clojure routine but it always results in a null pointer. How can I eliminate the errors?

(defn loopthru [n] (
  (if-not (empty? n) (
       (println (first n))
       (loopthru (rest n))
  ))
))
(loopthru [1 2 3 4 5 6])

Thanks, Greg

3 Answers 3

6

As everyone pointed out, you have double parentheses around your if-not macro which is not correct. (Double parentheses are rarely correct in Clojure, unlike Scheme.) But there is also another problem in your if special form. There should be a do special form which evaluates the s-expressions in order.

(defn loopthru [n]
  (if-not (empty? n)
    (do (println (first n))
     (loopthru (rest n)))))

A couple of other things. Use when / when-not in cases where you do not have an else block in your if statement. In fact, using when-not in this case eliminates the need for do since there is no ambiguity in the s-expressions with respect to the conditional. And I have to mention the obligatory comment that recursion in this case will chew up stack space so use recur instead

(defn loopthru [n]
  (when-not (empty? n)
    (println (first n))
    (recur (rest n))))
Sign up to request clarification or add additional context in comments.

2 Comments

another alternative (maybe more idiomatic?) would be use (when (seq n) ...) instead (when-not (empty? n) ...)
Julian, it makes a difference if the "do" is added, doesn't it? No one else suggested that. That gave the the desired result. Maybe you tested before posting your answer? Thanks.
3
(defn loopthru [col]
  (doseq [n col] (println n)))

(defn loopthru [f col]
  (doseq [item col] (f item)))

Comments

0

The pair of parentheses around the body of the function should be omitted. Then it will work.

3 Comments

I removed the pair of parens but it didn't help
You have two too many pairs. Parens are not for grouping, they are for calling functions. (defn loopthru [n] (if-not (empty? n) (println (first n)) (loopthru (rest n))))
@amalloy, the code as you have it does not print the numbers 1 through six

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.