Yar
Yar

Reputation: 7476

clojure loop/recur in a range

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?

Upvotes: 0

Views: 125

Answers (1)

Sam Estep
Sam Estep

Reputation: 13354

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

Upvotes: 3

Related Questions