Search code examples
clojure

How to break out of a doseq?


I am relatively new to Clojure. I was trying to use doseq by writing a simple method isPrime which will return true or false.

How do I return false and break out of the doseq call if I find a particular number to be dividing n by remainder 0?

and how do I know I went all the way till the end of the list ?

Do I have to always go through all the elements in the list ?

Also should I use an atom as a flag to keep track of whether I found one number that divides n or not?

I am stuck at a point:

(defn isPrime
  #_=>  "Is the given number prime"
  #_=>  [n]
  #_=>  (doseq [i 2 (int (inc (Math/sqrt n)))]
  #_=>    (if (= (mod n i) 0)

Solution

  • There is probably a way to break out of a doseq by using an exception, but you really shouldn't use doseq in such a case. It is not designed for such problems.

    The standard library function not-any?, on the other hand, does exactly what you need. In similar cases, you should also consider not-any?'s siblings, some?, every?, and not-every?.

    Here's an example solution that correctly implements the (very naive) algorithm from your code:

    (defn prime?
      "Returns true if n is a prime number."
      [n]
      (not-any? #(zero? (mod n %))
                (range 2 (inc (Math/sqrt n)))))