I'm trying to implement a function that returns Bernoulli numbers:
(defn binom [N K]
(if (or (= K 0) (= N K))
(int 1)
(int (+ (binom (- N 1) (- K 1))
(binom (- N 1) K)))))
(defn bernoulli [M]
(if (= M 0)
(int 1)
(for [K (range 0 (- M 1))]
(* (binom M K)
(bernoulli K)))))
(println (bernoulli 5))
(Obviously it's not correctly implemented yet, but that is irrelevant to my question)
When I run this program, I get the exception java.lang.ClassCastException: clojure.lang.LazySeq cannot be cast to java.lang.Number.
However, if I replace the recursive call (bernoulli K) with (bernoulli 0), the code runs fine.
What is going on here? Why can my binom function handle K as a number alright, but my bernoulli function can't?
Here's the entire error message:
$ clojure bern.clj
(Exception in thread "main" java.lang.ClassCastException: clojure.lang.LazySeq cannot be cast to java.lang.Number
at clojure.lang.Numbers.multiply(Numbers.java:146)
at user$bernoulli$iter__3__7$fn__8$fn__9.invoke(x2.clj:21)
at user$bernoulli$iter__3__7$fn__8.invoke(x2.clj:18)
at clojure.lang.LazySeq.sval(LazySeq.java:42)
at clojure.lang.LazySeq.seq(LazySeq.java:60)
at clojure.lang.RT.seq(RT.java:473)
at clojure.core$seq.invoke(core.clj:133)
at clojure.core$print_sequential.invoke(core_print.clj:46)
at clojure.core$fn__5270.invoke(core_print.clj:140)
at clojure.lang.MultiFn.invoke(MultiFn.java:167)
at clojure.core$pr_on.invoke(core.clj:3266)
at clojure.core$pr.invoke(core.clj:3278)
at clojure.lang.AFn.applyToHelper(AFn.java:161)
at clojure.lang.RestFn.applyTo(RestFn.java:132)
at clojure.core$apply.invoke(core.clj:601)
at clojure.core$prn.doInvoke(core.clj:3311)
at clojure.lang.RestFn.applyTo(RestFn.java:137)
at clojure.core$apply.invoke(core.clj:601)
at clojure.core$println.doInvoke(core.clj:3331)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at user$eval18.invoke(x2.clj:29)
at clojure.lang.Compiler.eval(Compiler.java:6514)
at clojure.lang.Compiler.load(Compiler.java:6955)
at clojure.lang.Compiler.loadFile(Compiler.java:6915)
at clojure.main$load_script.invoke(main.clj:283)
at clojure.main$script_opt.invoke(main.clj:343)
at clojure.main$main.doInvoke(main.clj:427)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at clojure.lang.Var.invoke(Var.java:415)
at clojure.lang.AFn.applyToHelper(AFn.java:161)
at clojure.lang.Var.applyTo(Var.java:532)
at clojure.main.main(main.java:37)
The second condition in bernoulli is a call to for, which returns a lazy-seq, but you are trying to invoke an arithmetic operation to it, which is simply invalid. Perhaps you want to sum the result with (apply + (for ...)), which uses the values returned by for as args to + (I don't know the specific algorithm off the top of my head, maybe you want an average or a product rather than a sum...).
Related
(defn fac [n]
(def result 1)
(loop [i n c 1]
(if (<= c 5)
result
(recur (* c i) (inc c))
)
)
(println result)
)
(fac 5)
Error:Exception in thread "main" java.lang.IllegalArgumentException: loop requires a vector for its binding.
I am trying to write a function that evaluates a numbers factorial. Where is my mistake? It gives me 1 as answer
At first sight:
Don't use a def inside a defn.
The REPL will print the result of evaluating a function. Use it.
This gets us to
(defn fac [n]
(loop [i n c 1]
(if (<= c 5)
result
(recur (* c i) (inc c)))))
... which doesn't compile, because result is floating.
There are a few corrections required:
Return i, not result.
Start i at 1, not n.
Turn the test around: > instead of <=.
We end up with
(defn fac [n]
(loop [i 1, c 1]
(if (> c n)
i
(recur (* c i) (inc c)))))
... which works:
(fac 5)
=> 120
Edited to correct one-off error and improve explanation.
Still very new to Clojure and programming in general so forgive the stupid question.
The problem is:
Find n and k such that the sum of numbers up to n (exclusive) is equal to the sum of numbers from n+1 to k (inclusive).
My solution (which works fine) is to define the following functions:
(defn addd [x] (/ (* x (+ x 1)) 2))
(defn sum-to-n [n] (addd(- n 1)))
(defn sum-to-k [n=1 k=4] (- (addd k) (addd n)))
(defn is-right[n k]
(= (addd (- n 1)) (sum-to-k n k)))
And then run the following loop:
(loop [n 1 k 2]
(cond
(is-right n k) [n k]
(> (sum-to-k n k) (sum-to-n n) )(recur (inc n) k)
:else (recur n (inc k))))
This only returns one answer but if I manually set n and k I can get different values. However, I would like to define a function which returns a lazy sequence of all values so that:
(= [6 8] (take 1 make-seq))
How do I do this as efficiently as possible? I have tried various things but haven't had much luck.
Thanks
:Edit:
I think I came up with a better way of doing it, but its returning 'let should be a vector'. Clojure docs aren't much help...
Heres the new code:
(defn calc-n [n k]
(inc (+ (* 2 k) (* 3 n))))
(defn calc-k [n k]
(inc (+ (* 3 k)(* 4 n))))
(defn f
(let [n 4 k 6]
(recur (calc-n n k) (calc-k n k))))
(take 4 (f))
Yes, you can create a lazy-seq, so that the next iteration will take result of the previous iteration. Here is my suggestion:
(defn cal [n k]
(loop [n n k k]
(cond
(is-right n k) [n k]
(> (sum-to-k n k) (sum-to-n n) )(recur (inc n) k)
:else (recur n (inc k)))))
(defn make-seq [n k]
(if-let [[n1 k1] (cal n k)]
(cons [n1 k1]
(lazy-seq (make-seq (inc n1) (inc k1))))))
(take 5 (make-seq 1 2))
;;=> ([6 8] [35 49] [204 288] [1189 1681] [6930 9800])
just generating lazy seq of candidatess with iterate and then filtering them should probably be what you need:
(def pairs
(->> [1 2]
(iterate (fn [[n k]]
(if (< (sum-to-n n) (sum-n-to-k n k))
[(inc n) k]
[n (inc k)])))
(filter (partial apply is-right))))
user> (take 5 pairs)
;;=> ([6 8] [35 49] [204 288] [1189 1681] [6930 9800])
semantically it is just like manually generating a lazy-seq, and should be as efficient, but this one is probably more idiomatic
If you don't feel like "rolling your own", here is an alternate solution. I also cleaned up the algorithm a bit through renaming/reformating.
The main difference is that you treat your loop-recur as an infinite loop inside of the t/lazy-gen form. When you find a value you want to keep, you use the t/yield expression to create a lazy-sequence of outputs. This structure is the Clojure version of a generator function, just like in Python.
(ns tst.demo.core
(:use tupelo.test )
(:require [tupelo.core :as t] ))
(defn integrate-to [x]
(/ (* x (+ x 1)) 2))
(defn sum-to-n [n]
(integrate-to (- n 1)))
(defn sum-n-to-k [n k]
(- (integrate-to k) (integrate-to n)))
(defn sums-match[n k]
(= (sum-to-n n) (sum-n-to-k n k)))
(defn recur-gen []
(t/lazy-gen
(loop [n 1 k 2]
(when (sums-match n k)
(t/yield [n k]))
(if (< (sum-to-n n) (sum-n-to-k n k))
(recur (inc n) k)
(recur n (inc k))))))
with results:
-------------------------------
Clojure 1.10.1 Java 13
-------------------------------
(take 5 (recur-gen)) => ([6 8] [35 49] [204 288] [1189 1681] [6930 9800])
You can find all of the details in the Tupelo Library.
This first function probably has a better name from math, but I don't know math very well. I'd use inc (increment) instead of (+ ,,, 1), but that's just personal preference.
(defn addd [x]
(/ (* x (inc x)) 2))
I'll slightly clean up the spacing here and use the dec (decrement) function.
(defn sum-to-n [n]
(addd (dec n)))
(defn sum-n-to-k [n k]
(- (addd k) (addd n)))
In some languages predicates, functions that return booleans,
have names like is-odd or is-whatever. In clojure they're usually
called odd? or whatever?.
The question-mark is not syntax, it's just part of the name.
(defn matching-sums? [n k]
(= (addd (dec n)) (sum-n-to-k n k)))
The loop special form is kind of like an anonymous function
for recur to jump back to. If there's no loop form, recur jumps back
to the enclosing function.
Also, dunno what to call this so I'll just call it f.
(defn f [n k]
(cond
(matching-sums? n k) [n k]
(> (sum-n-to-k n k) (sum-to-n n)) (recur (inc n) k)
:else (recur n (inc k))))
(comment
(f 1 2) ;=> [6 8]
(f 7 9) ;=> [35 49]
)
Now, for your actual question. How to make a lazy sequence. You can use the lazy-seq macro, like in minhtuannguyen's answer, but there's an easier, higher level way. Use the iterate function. iterate takes a function and a value and returns an infinite sequence of the value followed by calling the function with the value, followed by calling the function on that value etc.
(defn make-seq [init]
(iterate (fn [n-and-k]
(let [n (first n-and-k)
k (second n-and-k)]
(f (inc n) (inc k))))
init))
(comment
(take 4 (make-seq [1 2])) ;=> ([1 2] [6 8] [35 49] [204 288])
)
That can be simplified a bit by using destructuring in the argument-vector of the anonymous function.
(defn make-seq [init]
(iterate (fn [[n k]]
(f (inc n) (inc k)))
init))
Edit:
About the repeated calculations in f.
By saving the result of the calculations using a let, you can avoid calculating addd multiple times for each number.
(defn f [n k]
(let [to-n (sum-to-n n)
n-to-k (sum-n-to-k n k)]
(cond
(= to-n n-to-k) [n k]
(> n-to-k to-n) (recur (inc n) k)
:else (recur n (inc k)))))
The following closure computation overflows despite the use of big integers:
(defn binomial-coefficient [n k]
(let [rprod (fn [a b] (reduce * (range a (inc b))))]
(/ (rprod (- n k -1) n) (rprod 1 k))))
(binomial-coefficient 100N 50N)
I could not figure out where the overflow happens. For example, executing rprod by itself seems to work.
NB: the binomial coefficient code was taken from Rosetta Code.
The problem is that you're calling (rprod 1 k) with an integer 1 and not a bigint 1N:
(defn binomial-coefficient [n k]
(let [rprod (fn [a b] (reduce * (range a (inc b))))]
(/ (rprod (- n k -1) n) (rprod 1N k))))
(binomial-coefficient 100N 50N)
The problem lays in range function:
=> (range 1 10N)
(1 2 3 4 5 6 7 8 9)
=> (range 1N 10)
(1N 2N 3N 4N 5N 6N 7N 8N 9N)
Alternative solution is to use *', -' and inc' instead of ordinary *, - and inc operators, because they have build-in support for arbitrary precision and never overflow:
(defn binomial-coefficient [n k]
(let [rprod (fn [a b] (reduce *' (range a (inc' b))))]
(/ (rprod (-' n k -1) n) (rprod 1 k))))
(binomial-coefficient 100 50)
Helo, In an effort to learn clojure, I have taken an interest in clojure.core functions that act on sequences. Recently, I noticed some odd behaviour and would like an explaination of the difference between the folling expressions:
What I'm trying to do is this:
user=> (reduce + (take-while (partial > 1000) (iterate inc 1)))
499500
However, when I store (iterate inc 1) with def a get an error:
user=> (def a (iterate inc 1))
#'user/a
user=> (reduce + (take-while (partial > 1000) (a)))
java.lang.ClassCastException: clojure.lang.Cons cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)
Could someone please explain what the difference between storing iterate inc 1 and using it directly in the expression? I know that a is a lazy sequence but am missing something...
Thank you very much for your time.
You should be doing
(reduce + (take-while (partial > 1000) a))
(a) attempts to call a, but it's not a function.
How do I do mutually recursive definitions in Clojure?
Here is a code in Scala to find prime numbers which uses recursive definitions:
val odds: Stream[Int] = cons(3, odds map { _ + 2 })
val primes: Stream[Int] = cons(2, odds filter isPrime)
def primeDivisors(n: Int) =
primes takeWhile { _ <= Math.ceil(Math.sqrt(n))} filter { n % _ == 0 }
def isPrime(n: Int) = primeDivisors(n) isEmpty
primes take 10
I translated this to Clojure:
(def odds (iterate #(+ % 2) 3))
(def primes (cons 2 (filter is-prime odds)))
(defn prime-divisors [n]
(filter #(zero? (mod n %))
(take-while #(<= % (Math/ceil (Math/sqrt n)))
primes)))
(defn is-prime [n] (empty? (prime-divisors n)))
(take 10 primes)
But writing the definitions in the Clojure REPL one by one gives
java.lang.Exception: Unable to resolve symbol: is-prime in this context (NO_SOURCE_FILE:8)
after I write (def primes (cons 2 (filter is-prime odds))).
Is there a way to do mutually recursive definitions in Clojure?
You need to (declare is-prime) before the first time you reference it.
This is referred to as a "forward declaration".
Greg's answer is correct. However you have to rearrange your code: (def odds ...) (declare primes) (defn prime-divisors ...) (defn prime? ...) (def primes ...). This should do the trick.
The problem is, that the definition of primes is not a function. It is executed immediately and hence tries to dereference the prime? Var which is not bound, yet. Hence the exception. Re-arranging should take care of that.
(Disclaimer: I haven't checked that the code works with the re-arrangement.)
And I think prime? is broken. (prime? 2) should give false, no?