Reputation: 9051
I wrote a simple python
function for my friend to tell why a number is now a prime:
def why_not_prime(n):
if n==2:
print(n, "is a prime.")
for i in range(2,n):
if n%i == 0:
print(n, "is not a prime because it could be divided by", i,".")
break
else:
print(n, "is a prime.")
break
I try to convert it to Clojure
, but I couldn't find the way. I've no idea how to handle the for i in range(2,n)
. What's the usual way to do it?
Upvotes: 0
Views: 717
Reputation: 3014
In Clojure, there's really no universal answer to this as it's decided by why you want to iterate through those numbers.
You might want to produce some value for each of the numbers and then collect them in a list, in which case you want to use map
or for
. You might want to "summarize" them in some way (like adding them all together) in which case you'd want to use something like reduce
.
In this case you want a special kind of summary; you want to know if there is some value in the range which is "appropriate" (in this case a divisor of n
). There is a core function for this kind of use case called some
, but it needs a function to tell it what is an "appropriate" value. There's no base function which does all we want, but we can just create one.
(defn why-not-prime [n]
(let[checker (fn [divisor] ;; A local function under the name checker, with one argument
(if (= 0 (mod n divisor));; If that argument is a divisor of n
divisor ;;then return it
false)) ;; otherwise return false - this value wasn't "appropriate"
witness (some checker (range 2 n))] ;; witness will be the first value that satisfies checker
;if there isn't such a value, witness is nil
(if witness
(str n " is composite because it can be divided by " witness)
(str n " is prime."))))
Now, this redefines your problem slightly, in that it doesn't print any message, but only return a string containing one. This is a more idiomatic formulation in a functional language where you usually defer side effects like printing as long as you can. If you want it to print, you can just wrap the entire function body with a println
.
Upvotes: 3