Functional way to validate a number in a clojure
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.
source to share
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])
source to share