Functional way to validate a number in a clojure

What would be a more correct functional way to write the following code that checks if a number is prime or not:

(defn prime? [n]
  (loop [k 2]
    (cond
     (< k n) (if (not= 0 (mod n k))
               (recur (inc k))
               (println n "is not prim"))
     :else (println n "is prim"))))

      

+3


source to share


2 answers


Regardless of which algorithm you use to test primitiveness, the "correct function path" will prime?

return true

or for your function false

. Anyway, your function returns nil

and has side effects (prints something).



Then you can do (println (prime? x))

to check for a specific number, and have side effects limited to that single expression.

+8


source


Simplest way to use standard library functions like every?

and range

:

(defn divisible? [a b]
  (zero? (mod a b)))

(defn prime? [n]
  (and (> n 1) (not-any? (partial divisible? n) (range 2 n))))

      

and refactoring the I / O into a separate function for more reuse:



(defn format-primality [n]
  (str n " " (if (prime? n) "is prim" "is not prim")))

(def print-primality
  (comp println format-primality))

      

Example:

user=> (map (fn [n] [n (prime? n)]) (range 1 15))
([1 false] [2 true] [3 true] [4 false] [5 true] [6 false] [7 true]
 [8 false] [9 false] [10 false] [11 true] [12 false] [13 true] [14 false])

      

+4


source







All Articles