0

I want to do a loop/recur in a range of 3 to 11:

(loop [itr 3]
  (if (and (< itr 11) (= 0 (mod itr 4)))
    (println itr)
    (recur (inc itr))
    ))

As expected, it will return 4. The problem is when I am looking for something that doesn't have any match:

(loop [itr 2]
  (if (and (< itr 3) (= 0 (mod itr 4)))
    (println itr)
    (recur (inc itr))
    ))

This will crash the REPL without returning the nil. Is there a way to add something like an else statement to this loop, so if there is no match, it returns a nil?

1 Answer 1

3

Instead of loop/recur, consider using the higher-level functions at your disposal:

(first (filter #(zero? (mod % 4)) (range 3 11)))
;=> 4
(first (filter #(zero? (mod % 4)) (range 2 3)))
;=> nil
Sign up to request clarification or add additional context in comments.

Comments

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.