clojure - is-prime? prime numbers - clojure

function named is-prime? which takes an input n and returns true if n is
prime, and false otherwise. This function should check to see if n is 1 or 2 and
respond accordingly; if not, it should call your no-divisors?.
(defn divides? [div n] (zero? (mod n div)))
(defn no-divisors? [n]
(->> (range 2 n)
(filter #(divides? % n))
empty?))
problem code below
(defn is-prime? [n]
(and (> n 1) (not-any? (filter #(no-divisors? % n)) (range 2 n))))
/// current output///
(is-prime? 1)
=> false
(is-prime? 2)
=> true
(is-prime? 3)
=> false
(is-prime? 4)
=> false
(is-prime? 101)
=> false
/// current output///
/// required output ///
(is-prime? 1)
=> false
(is-prime? 2)
=> true
(is-prime? 3)
=> true
(is-prime? 4)
=> false
(is-prime? 101)
=> true
/// required output ///
help would be appreciated

The no-divisors? is redundant.
(letfn [(divides? [m n] (zero? (rem m n)))
(prime? [n] (and (< 1 n) (not-any? #(divides? n %) (range 2 n))))]
(prn (for [i (range 100)
:when (prime? i)] i)))

Related

Convert pseudo-code with nested for-loops to Clojure

I want to implement this psuedo code in Clojure:
function(n)
B[0] <-- 1
for m <-- 1 to n do
B[m] <-- 0
for k <-- 0 to m - 1 do
B[m] <-- B[m] − binom(m+1, k) * B[k]
B[m] <-- B[m]/(m+1)
return B[n]
My first thought was to do something like this:
(defn foo [n]
(if (= n 0)
(int 1)
(for [k (range 0 (- n 1))]
(* (binom (+ n 1) k)
(foo k)))))
but now I'm stuck and I don't know how to continue. The nested loops confuse me a lot when I try to translate them to Clojure.
I'd really appreciate some help on how to write this code in Clojure, I feel a bit lost.
Thanks in advance!
Some algorithms are naturally imperative in nature. Don't be afraid to write imperative code if that is the easiest solution, rather than trying to "force fit" the algorithm into a functional style.
This algorithm could easily use a mutable atom to store the B array:
(defn factorial [x]
(reduce * (range 2 (inc x))))
(defn binom [n k]
(/ (factorial n)
(factorial k) (factorial (- n k))))
(defn bernoulli [n]
(let [B (atom (vec (repeat n 0)))] ; allocate B[0]..B[n-1] = zeros
(swap! B assoc 0 1) ; B[0] = 1
(doseq [m (range 1 (inc n))] ; 1..n
(swap! B assoc m 0) ; B[m] = 0
(doseq [k (range m)] ; 0..(m-1)
(swap! B #(assoc % m ; B[m] = ...
(-
(get % m) ; B[m]
(*
(binom (inc m) k)
(get % k)))))) ; B[k]
(swap! B update m ; B[m] = B[m] ...
#(/ % (inc m))))
(get #B n)))
(dotest
(dotimes [i 10]
(spyx [i (bernoulli i)])))
with result
[i (bernoulli i)] => [0 1]
[i (bernoulli i)] => [1 -1/2]
[i (bernoulli i)] => [2 1/6]
[i (bernoulli i)] => [3 0N]
[i (bernoulli i)] => [4 -1/30]
[i (bernoulli i)] => [5 0N]
[i (bernoulli i)] => [6 1/42]
[i (bernoulli i)] => [7 0N]
[i (bernoulli i)] => [8 -1/30]
[i (bernoulli i)] => [9 0N]
You could also use with-local-vars for some algorithms, or even drop down into a (mutable) Java array. You can see an example of that in this mutable Java matrix example
The given pseudocode computes the nth Bernoulli number. It uses all the previous Bernoulli numbers to compute the result. Much like the factorial function, this lends itself to a recursive algorithm which may be implemented with memoize to avoid re-computation of earlier numbers:
(def factorial
"Returns n!."
(memoize (fn [n]
(if (< 1 n)
(* n (factorial (dec n)))
1N))))
(def bernoulli
"Returns the nth Bernoulli number."
(memoize (fn [n]
(if (zero? n)
1
(let [n! (factorial n)
term #(/ (* n! (bernoulli %))
(factorial %)
(factorial (- n % -1)))
terms (map term (range n))]
(reduce - 0 terms))))))
(map bernoulli (range 9)) ; => (1 -1/2 1/6 0N -1/30 0N 1/42 0N -1/30)
The pseudo code uses plenty of in-place updates which makes it a bit hard to read. But essentially, the code computes a list of numbers where every number is computed from the previous numbers in the list. And then we pick one of the numbers in the list.
I would implement this algorithm like
(defn compute-next-B [B]
(let [m (count B)
m+1 (inc m)
terms (map-indexed (fn [k Bk] (- (* Bk (binom m+1 k)))) B)]
(conj B (/ (apply + terms) m+1))))
(defn foo [n]
(->> [1]
(iterate compute-next-B)
(drop n)
first
last))
The outer loop from the pseudo code is the lazy sequence produced by (iterate compute-next-B ...). The inner loop from the pseudo code is the iteration inside (apply + terms) on the lazy sequence terms.

Compose multiple predicate functions into one

Is it possible to compose for example:
(defn- multiple-of-three? [n] (zero? (mod n 3))
(defn- multiple-of-five? [n] (zero? (mod n 5))
into:
multiple-of-three-or-five?
so I can use it for filtering:
(defn sum-of-multiples [n]
(->> (range 1 n)
(filter multiple-of-three-or-five?)
(reduce +)))
Also I don't want to define it like this:
(defn- multiple-of-three-or-five? [n]
(or (multiple-of-three? n)
(multiple-of-five? n)))
For example with Javascript module Ramda it would be achieved as: http://ramdajs.com/docs/#either
const multipleOfThreeOrFive = R.either(multipleOfThree, multipleOfFive)
Sure, in Clojure this is some-fn.
(def multiple-of-three-or-five?
(some-fn multiple-of-three? multiple-of-five?))
(multiple-of-three-or-five? 3) ; => true
(multiple-of-three-or-five? 4) ; => false
(multiple-of-three-or-five? 5) ; => true

Error on Clojure (unbound fn)

Im starting to learn Clojure from the scratch and im stucked on my function. Im trying to find the sum of all the multiples of 3 or 5 below 1000. THis is what i did.
(defn suma [x sum]
(cond
(= (/ x 3) 0)(let [sum (+ sum x)])
(= (/ x 5) 0)(let [sum (+ sum x)])))
(defn main[]
(def sum 0)
(def x 3)
(while(< x 1001)
(do
(suma sum x)
(let [x (+ x 1)]))
(str "Total = " sum)))
I tried several things, but i cant figure out what's wrong....
Any help will be apreciated.
Thanks
EDIT:
Fixed, the problem was on the let, it was not updating the value of the data. Here the solution:
(defn suma [x sum]
(cond
(zero? (mod x 3))(alter-var-root #'sum (constantly (+ sum x)))
(zero? (mod x 5))(alter-var-root #'sum (constantly (+ sum x)))))
(defn main[]
(def sum 0)
(def x 3)
(while(< x 1001)
(do
(suma x sum)
(alter-var-root #'x inc)))
(str "TOTAL = " sum))
A simple solution using the sequence library is
(->> (concat
(range 0 1000 3)
(range 0 1000 5))
distinct
(apply +))
If you want to do it in an iterative style, Don't use while, which depends on side effects. Use loop and recur, which effect a primitive form of recursion called tail recursion:
(defn divides? [i j]
(zero? (mod j i)))
(loop [answer 0, n 0]
(if (< n 1000)
(recur
(if (or (divides? 3 n) (divides? 5 n))
(+ answer n)
answer)
(inc n))
answer))
Both the above produce the same answer.
Here is an outline using a more functional style. Of course, there is more than one way to do it (TM). :)
> lein repl
user=> (def data (range 20))
user=> data
(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)
user=> (defn is-mul-3? [x] (zero? (mod x 3)))
user=> (mapv is-mul-3? data)
[true false false true false false true false false true false false true false false true false false true false]
user=> (defn is-mul-5? [x] (zero? (mod x 5)))
user=> (mapv is-mul-5? data)
[true false false false false true false false false false true false false false false true false false false false]
user=> (defn is-mul-3-or-5? [x] (or (is-mul-3? x) (is-mul-5? x)))
user=> (mapv is-mul-3-or-5? data)
[true false false true false true true false false true true false true false false true false false true false]
user=> (def only-3s-and-5s (filterv is-mul-3-or-5? data))
user=> only-3s-and-5s
[0 3 5 6 9 10 12 15 18]
user=> (apply + only-3s-and-5s)
78
Update:
Here is a more imperitive version. Clojure values (like in let are usually immutable). You must use an atom if you want something like a
mutable Java variable:
(ns clj.core
(:gen-class))
(defn is-mul-3? [x]
(zero? (mod x 3)))
(defn is-mul-5? [x]
(zero? (mod x 5)))
(defn is-mul-3-or-5? [x]
(or (is-mul-3? x)
(is-mul-5? x)))
(defn sum-3s-and-5s [limit]
(let [cum-sum (atom 0) ]
(doseq [curr-val (range limit)]
(if (is-mul-3-or-5? curr-val)
(swap! cum-sum + curr-val)))
#cum-sum ))
(defn -main [& args]
(println "cumsum = " (sum-3s-and-5s 20))
)
with result:
~/clj > lein run
cumsum = 78

Genetic programming Clojure

I've pasted the code on this page in an IDE and it works. The problem is that when I replace the definition of target-data with this vector of pairs* it gives me this error**.
(vector [[1 2]
[2 3]
[3 4]
[4 5]] ) ; *
UnsupportedOperationException nth not supported on this type: core$vector clojure.lang.RT.nthFrom (RT.java:857) **
What should I do to use my own target-data?
UPDATED FULL CODE:
(ns evolvefn.core)
;(def target-data
; (map #(vector % (+ (* % %) % 1))
; (range -1.0 1.0 0.1)))
;; We'll use input (x) values ranging from -1.0 to 1.0 in increments
;; of 0.1, and we'll generate the target [x y] pairs algorithmically.
;; If you want to evolve a function to fit your own data then you could
;; just paste a vector of pairs into the definition of target-data instead.
(def target-data
(vec[1 2]
[2 3]
[3 4]
[4 5]))
;; An individual will be an expression made of functions +, -, *, and
;; pd (protected division), along with terminals x and randomly chosen
;; constants between -5.0 and 5.0. Note that for this problem the
;; presence of the constants actually makes it much harder, but that
;; may not be the case for other problems.
(defn random-function
[]
(rand-nth '(+ - * pd)))
(defn random-terminal
[]
(rand-nth (list 'x (- (rand 10) 5))))
(defn random-code
[depth]
(if (or (zero? depth)
(zero? (rand-int 2)))
(random-terminal)
(list (random-function)
(random-code (dec depth))
(random-code (dec depth)))))
;; And we have to define pd (protected division):
(defn pd
"Protected division; returns 0 if the denominator is zero."
[num denom]
(if (zero? denom)
0
(/ num denom)))
;; We can now evaluate the error of an individual by creating a function
;; built around the individual, calling it on all of the x values, and
;; adding up all of the differences between the results and the
;; corresponding y values.
(defn error
[individual]
(let [value-function (eval (list 'fn '[x] individual))]
(reduce + (map (fn [[x y]]
(Math/abs
(- (value-function x) y)))
target-data))))
;; We can now generate and evaluate random small programs, as with:
;; (let [i (random-code 3)] (println (error i) "from individual" i))
;; To help write mutation and crossover functions we'll write a utility
;; function that injects something into an expression and another that
;; extracts something from an expression.
(defn codesize [c]
(if (seq? c)
(count (flatten c))
1))
(defn inject
"Returns a copy of individual i with new inserted randomly somwhere within it (replacing something else)."
[new i]
(if (seq? i)
(if (zero? (rand-int (count (flatten i))))
new
(if (< (rand)
(/ (codesize (nth i 1))
(- (codesize i) 1)))
(list (nth i 0) (inject new (nth i 1)) (nth i 2))
(list (nth i 0) (nth i 1) (inject new (nth i 2)))))
new))
(defn extract
"Returns a random subexpression of individual i."
[i]
(if (seq? i)
(if (zero? (rand-int (count (flatten i))))
i
(if (< (rand) (/ (codesize (nth i 1))
(- (codesize i)) 1))
(extract (nth i 1))
(extract (nth i 2))))
i))
;; Now the mutate and crossover functions are easy to write:
(defn mutate
[i]
(inject (random-code 2) i))
(defn crossover
[i j]
(inject (extract j) i))
;; We can see some mutations with:
;; (let [i (random-code 2)] (println (mutate i) "from individual" i))
;; and crossovers with:
;; (let [i (random-code 2) j (random-code 2)]
;; (println (crossover i j) "from" i "and" j))
;; We'll also want a way to sort a populaty by error that doesn't require
;; lots of error re-computation:
(defn sort-by-error
[population]
(vec (map second
(sort (fn [[err1 ind1] [err2 ind2]] (< err1 err2))
(map #(vector (error %) %) population)))))
;; Finally, we'll define a function to select an individual from a sorted
;; population using tournaments of a given size.
(defn select
[population tournament-size]
(let [size (count population)]
(nth population
(apply min (repeatedly tournament-size #(rand-int size))))))
;; Now we can evolve a solution by starting with a random population and
;; repeatedly sorting, checking for a solution, and producing a new
;; population.
(defn evolve
[popsize]
(println "Starting evolution...")
(loop [generation 0
population (sort-by-error (repeatedly popsize #(random-code 2)))]
(let [best (first population)
best-error (error best)]
(println "======================")
(println "Generation:" generation)
(println "Best error:" best-error)
(println "Best program:" best)
(println " Median error:" (error (nth population
(int (/ popsize 2)))))
(println " Average program size:"
(float (/ (reduce + (map count (map flatten population)))
(count population))))
(if (< best-error 0.1) ;; good enough to count as success
(println "Success:" best)
(recur
(inc generation)
(sort-by-error
(concat
(repeatedly (* 1/2 popsize) #(mutate (select population 7)))
(repeatedly (* 1/4 popsize) #(crossover (select population 7)
(select population 7)))
(repeatedly (* 1/4 popsize) #(select population 7)))))))))
;; Run it with a population of 1000:
(evolve 1000)
And the error is:
(evolve 1000)
Starting evolution...
IllegalArgumentException No matching method found: abs clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:80)
evolvefn.core=>

Clojure: Why does if-let only allow 2 forms in the binding vector?

When I use if-let like
(if-let [a 2 b nil] (+ a b))
I get an IllegalArgumentException:
clojure.core/if-let requires exactly 2 forms in binding vector...
Similar for when-let...
This is not what I would expect. If-let could try all bindings and break when one fails and evaluate the else expression.
The same complaint can be found in the comments at clojuredocs. I found an answer here which did not really satisfy since the poster seems to have the equivalent of a nested if-let-structure in mind.
What reasons are there to limit the bindings of the *-let macros?
UPDATE:
As it seems to be unclear, what my expectations of if-let are:
It should evaluate all bindings sequentially.
When all succeed, it should evaluate the 'then'-case.
If one binding fails it should immediately break and evaluate the 'else'-case.
In case of failure the bindings, even succeeded ones, should not be available in the 'else'-expression
Try this out:
(defmacro if-let-multi
([bindings then-exp]
(let [values (take-nth 2 (rest bindings))]
`(if (and ~#values) (let ~bindings ~then-exp) false)))
([bindings then-exp else-exp]
(let [values (take-nth 2 (rest bindings))]
`(if (and ~#values) (let ~bindings ~then-exp) ~else-exp))))
Here it is in action:
user> (if-let-multi [a 2 b nil] (+ a b))
false
user> (if-let-multi [a 2 b 3] (+ a b))
5
user> (if-let-multi [a 2 b nil] (+ a b) "NO WAY")
"NO WAY"
if-let and let serve different purposes and if-let is not just a more restricted version of let. of instance if-let differs from let in that the value is bound only for the then clause and not the else.
user> (if-let [ans (+ 1 2 3)] ans :foo)
6
user> (if-let [ans (+ 1 2 3)] ans ans)
CompilerException java.lang.RuntimeException: Unable to resolve symbol: ans in this context, compiling:(NO_SOURCE_PATH:1)
user> (let [ans (+ 1 2 3)] ans ans)
6
if-let is intended to make life easier in the case where you are binding a value simply to test and use it.
Try this out.
(defmacro if-lets
([bindings true-expr] `(if-lets ~bindings ~true-expr nil))
([bindings true-expr false-expr]
(cond
(or (not (seq bindings)) (not (zero? (rem (count bindings) 2))))
`(throw (IllegalArgumentException. "if-lets requires 2 or multiple of 2 forms in binding vector in user:1"))
(seq (drop 2 bindings))
`(if-let ~(vec (take 2 bindings))
(if-lets ~(vec (drop 2 bindings))
~true-expr
~false-expr)
~false-expr)
:else
`(if-let ~(vec bindings)
~true-expr
~false-expr))))
This macro passed these tests below.
(deftest ut-if-lets
(testing "if-lets macro (normal cases)"
(is (= 0 (if-lets [x 0] x)))
(is (= 0 (if-lets [x 0] x 1)))
(is (= 1 (if-lets [x nil] x 1)))
(is (= 0 (if-lets [x 0 y x] y)))
(is (= 0 (if-lets [x 0 y x] y 1)))
(is (= 1 (if-lets [x nil y x] y 1)))
(is (= 0 (if-lets [x 0 y x z y] z)))
(is (= 0 (if-lets [x 0 y x z y] z 1)))
(is (= 1 (if-lets [x nil y x z y] y 1)))
(is (= true (if-lets [x true] true false)))
(is (= false (if-lets [x false] true false)))
(is (= true (if-lets [x true y true] true false)))
(is (= false (if-lets [x false y true] true false)))
(is (= false (if-lets [x true y false] true false)))
(is (= true (if-lets [x true y true z true] true false)))
(is (= false (if-lets [x false y true z true] true false)))
(is (= false (if-lets [x true y false z true] true false)))
(is (= false (if-lets [x true y true z false] true false)))
)
)
(deftest ut-if-lets-ab
(testing "if-lets macro (abnormal cases)"
(is (= (try (if-lets [] true false) (catch Exception e (.getMessage e)))
"if-lets requires 2 or multiple of 2 forms in binding vector in user:1"))
(is (= (try (if-lets [x] true false) (catch Exception e (.getMessage e)))
"if-lets requires 2 or multiple of 2 forms in binding vector in user:1"))
(is (= (try (if-lets [x true y] true false) (catch Exception e (.getMessage e)))
"if-lets requires 2 or multiple of 2 forms in binding vector in user:1"))
)
)