Why do I get an error from this code? - clojure

I´m new to clojure and am trying to break through some of the walls I keep running into. The code in question is the function v3 which should accept 4 arguments:
a min and a max integer, mi and ma, to use with the
random-numbers function to find numbers within a certain range,
another integer,cnt, to signify how many numbers I want in my
final list, and
tones, which is a list of integers that the randomized numbers have
to match once I've calculated modulo 12 of said numbers.
The function should run until o is a list of length cnt containing random numbers that are also in the tones list.
My document compiles just fine but when I want to run the function itself in a repl, for example using something like (v3 58 52 15 '(0 2 4 5 7 9)) I get the following error:
ClassCastException clojure.langLazySeq cannot be cast to java.lang.Number clojure.langNumbers.reminder (Numbers.java:173)
Here's my code
(defn random-numbers [start end n]
(repeatedly n #(+ (rand-int (- end start)) start)))
(defn m12 [input]
(mod input 12))
(defn in? [coll elm]
(some #(= elm %) coll))
(defn v3 [ma mi cnt tones]
(let [o '()]
(loop []
(when(< (count o) cnt)
(let [a (m12 (random-numbers mi ma 1))]
(if (in? tones a)
(conj o a)))))
(println o)))

First of all, it is more idiomatic Clojure to type the parentheses on the same line, and not in the "Java"-way.
When I debug your code I see it fails at the call to m12: random-numbers returns a sequence and the call to mod in m12 expects a number.
You can fix this issue by for example taking the first element from the sequence returned by random-numbers:
(defn v3
[ma mi cnt tones]
(let [o '()]
(loop []
(when (< (count o) cnt)
(let [a (m12 (first (random-numbers mi ma 1)))]
(if (in? tones a)
(conj o a)))))
(println o)))
/edit
I am not sure what your code is supposed to be doing, but this did not stop me to make some more changes. If you use a loop, you usually also see a recur to "recur" back to the loop target. Otherwise it does not do much. I added the following things:
a recur to the loop.
The let statement added to the loop vector (starting value).
println statements in the false clause of the if-statement.
Removed the first if-statement that checked the count
Changed list to vector. You would use a list over a vector when you create code structures structure (for example while writing macros).
See:
(defn v3
[ma mi cnt tones]
(loop [o []]
(if (< (count o) cnt)
(let [a (m12 (first (random-numbers mi ma 1)))]
(if (in? tones a)
(recur (conj o a))
(println "a not in tones, o:" o)))
(println "already " cnt "tones generated"))))
If you run (v3 58 52 4 [0 2 4 5 7 9]) (note I changed your 15 for cnt to 4 and changed the list to a vector) a few times you get for example the following output:
a not in tones, o: [4 4]
a not in tones, o: [9 5 5]
a not in tones, o: []
already 4 tones generated
a not in tones, o: [7]
Hope this helps.

I think I see what you are trying to do.
This is an exercise in automatic composition. Your v3 function is intended to generate a sequence of tones
in a range given by min and max.
with tone class drawn from a given set of tone classes (tones)
The m12 function returns the tone class of a tone, so let's call it that:
(defn tone-class [tone]
(mod tone 12))
While we're about it, I think your random-number function is easier to read if we add the numbers the other way round:
(defn random-number [start end]
(+ start (rand-int (- end start))))
Notice that the possible values include start but not end, just as the standard range does.
Apart from your various offences against clojure semantics, as described by #Erwin, there is a problem with the algorithm underlying v3. Were we to repair it (we will), it would generate a sequence of tone classes, not tones. Interpreted as tones, these do not move beyond the base octave, however wide the specified tone range.
A repaired v3
(defn v3 [mi ma cnt tones]
(let [tone-set (set tones)]
(loop [o '()]
(if (< (count o) cnt)
(let [a (tone-class (random-number mi ma))]
(recur (if (tone-set a) (conj o a) o)))
o))))
For a start, I've switched the order of mi and ma to conform with
range and the like.
We turn tones into a set, which therefore works as a
membership function.
Then we loop until the resulting sequence, o, is big enough.
We return the result rather than print it.
Within the loop, we recur on the same o if the candidate a doesn't fit, but on (conj o a) if it does. Let's try it!
(v3 52 58 15 '(0 2 4 5 7 9))
;(4 5 9 7 7 5 7 7 9 7 5 7 4 9 7)
Notice that neither 0 nor 2 appears, though they are in tones. That's because the tone range 52 to 58 maps into tone class range 4 to 10.
Now let's accumulate tones instead of tone classes. We need to move conversion inside the test, replacing ...
(let [a (tone-class (random-number mi ma))]
(recur (if (tone-set a) (conj o a) o)))
... with ...
(let [a (random-number mi ma)]
(recur (if (tone-set (tone-class a)) (conj o a) o)))
This gives us, for example,
(v3 52 58 15 '(0 2 4 5 7 9))
;(53 52 52 52 55 55 55 53 52 55 53 57 52 53 57)
An idiomatic v3
An idiomatic version would use the sequence library:
(defn v3 [mi ma cnt tones]
(let [tone-set (set tones)
numbers (repeatedly #(random-number mi ma))
in-tones (filter (comp tone-set tone-class) numbers)]
(take cnt in-tones)))
This generates the sequence front first. Though you can't tell by looking at the outcome, the repaired version above generates it back to front.
An alternative idiomatic v3
Using the ->> threading macro to capture the cascade of function calls:
(defn v3 [mi ma cnt tones]
(->> (repeatedly #(random-number mi ma))
(filter (comp (set tones) tone-class))
(take cnt)))

Related

How do i call a function from given two values in clojure one by one

Hi i am new to clojure i have written this function and there are few errors in it. i have got one function called 'checkFunction' it basically gets one paramtere and returns either true or false.
(defn getList [number1 number2]
(loop for x from number1 to number2
(recur (inc num) (if (checkFunction? x) (concat p [num]) p))))
i want the function above to take two paramters for example if i say 'get List 15 20' it should call check function with 15 16 17 18 19 20 and if checkFunction returns true it should put that number in the vector and return it or print it. so far i have got onto this but i am struggling a bit.
Any help or right direction would be very thankful.
If I understand your question, you're trying to filter a range of numbers according to some predicate. (For the sake of the example I set your check-function? to return true for odd numbers.)
(defn check-function? [n]
(odd? n))
(defn get-list [n1 n2]
(filter check-function? (range n1 (+ 1 n2))))
> (get-list 15 20)
(15 17 19)
If you are also interested in how the loop-recur works, here's a version more like what you were trying to do originally. But I will say that one of the nicest things about clojure is that you rarely have to do this!
(defn get-list-2 [n1 n2]
(loop [src (range n1 (+ 1 n2)) dest []]
(if (empty? src)
dest
(let [n (first src)
src (rest src)
dest (if (check-function? n) (conj dest n) dest)]
(recur src dest)))))
> (get-list-2 15 20)
[15 17 19]

clojure laziness: prevent unneded mapcat results to realize

Consider a query function q that returns, with a delay, some (let say ten) results.
Delay function:
(defn dlay [x]
(do
(Thread/sleep 1500)
x))
Query function:
(defn q [pg]
(lazy-seq
(let [a [0 1 2 3 4 5 6 7 8 9 ]]
(println "q")
(map #(+ (* pg 10) %) (dlay a)))))
Wanted behaviour:
I would like to produce an infinite lazy sequence such that when I take a value only needed computations are evaluated
Wrong but explicative example:
(drop 29 (take 30 (mapcat q (range))))
If I'm not wrong, it needs to evaluate every sequence because it really doesn't now how long the sequences will be.
How would you obtain the correct behaviour?
My attempt to correct this behaviour:
(defn getq [coll n]
(nth
(nth coll (quot n 10))
(mod n 10)))
(defn results-seq []
(let [a (map q (range))]
(map (partial getq a)
(iterate inc 0)))) ; using iterate instead of range, this way i don't have a chunked sequence
But
(drop 43 (take 44 (results-seq)))
still realizes the "unneeded" q sequences.
Now, I verified that a is lazy, iterate and map should produce lazy sequences, so the problem must be with getq. But I can't understand really how it breaks my laziness...perhaps does nth realize things while walking through a sequence? If this would be true, is there a viable alternative in this case or my solution suffers from bad design?

repeatedly apply a function until test no longer yields true

I wrote this code to nest a function n times and am trying to extend the code to handle a test. Once the test returns nil the loop is stopped. The output be a vector containing elements that tested true. Is it simplest to add a while loop in this case? Here is a sample of what I've written:
(defn nester [a inter f]
(loop [level inter expr a]
(if (= level 0) expr
(if (> level 0) (recur (dec level) (f expr))))))
An example input would be an integer 2, and I want to nest the inc function until the output is great than 6. The output should be [2 3 4 5 6 7].
(defn nester [a inter f test-fn]
(loop [level inter
expr a]
(if (or (zero? level)
(nil? (test-fn expr)))
expr
(recur (dec level)
(f expr)))))
If you also accept false (additionally to nil) from your test-fn, you could compose this more lazily:
(defn nester [a inter f test-fn]
(->> (iterate f a)
(take (inc inter))
(drop-while test-fn)
first))
EDIT: The above was answered to your initial question. Now that you have specified completely changed the meaning of your question:
If you want to generate a vector of all iterations of a function f over a value n with a predicate p:
(defn nester [f n p]
(->> (iterate f n)
(take-while p)
vec))
(nester inc 2 (partial > 8)) ;; predicate "until the output is greater than six"
;; translated to "as long as 8 is greater than
;; the output"
=> [2 3 4 5 6 7]
To "nest" or iterate a function over a value, Clojure has the iterate function. For example, (iterate inc 2) can be thought of as an infinite lazy list [2, (inc 2), (inc (inc 2)), (inc (inc (inc 2))) ...] (I use the [] brackets not to denote a "list"--in fact, they represent a "vector" in Clojure terms--but to avoid confusion with () which can denote a data list or an s-expression that is supposed to be a function call--iterate does not return a vector). Of course, you probably don't want an infinite list, which is where the lazy part comes in. A lazy list will only give you what you ask it for. So if you ask for the first ten elements, that's what you get:
user> (take 10 (iterate inc 2))
> (2 3 4 5 6 7 8 9 10 11)
Of course, you could try to ask for the whole list, but be prepared to either restart your REPL, or dispatch in a separate thread, because this call will never end:
user> (iterate inc 2)
> (2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
=== Shutting down REPL ===
=== Starting new REPL at C:\Users\Omnomnomri\Clojure\user ===
Clojure 1.5.0
user>
Here, I'm using clooj, and this is what it looks like when I restart my REPL. Anyways, that's all just a tangent. The point is that iterate answers the core of your question. The other part, stopping upon some test condition, involves take-while. As you might imagine, take-while is a lot like take, only instead of stopping after some number of elements, it stops upon some test condition (or in Clojure parlance, a predicate):
user> (take-while #(< % 10) (iterate inc 2))
> (2 3 4 5 6 7 8 9)
Note that take-while is exclusive with its predicate test, so that here once the value fails the test (of being less than 10), it excludes that value, and only includes the previous values in the return result. At this point, solving your example is pretty straightfoward:
user> (take-while #(< % 7) (iterate inc 2))
> (2 3 4 5 6)
And if you need it to be a vector, wrap the whole thing in a call to vec:
user> (vec (take-while #(< % 7) (iterate inc 2)))
> [2 3 4 5 6]

Recursive tree traversal in clojure producing breadth first, rather than depth first, results.

I'm trying to touch all potential dealer hands in blackjack, but when I kept blowing the stack, I realized things weren't as depth first as expected. So I tried similar code in ruby and it performed differently.
this code,
(def d [2 3 4 5 6 7 8 9 10 10 10 10 11])
(defn dig1 [lst depth tot]
(do
(print depth)
(if (< tot 17) (map #(dig1 (conj lst %) (+ depth 1) (+ tot %)) d)) ))
(dig1 [0] 0 0)
produces: 011111111111112222222222222...
I expected map to execute the function on d[0] and dig down rather than to see everything executed at a given level. I obviously don't understand what's going on. Do I need to make something lazy(er)? map produces lazy sequences, but apparently chunks them in groups of 32.
in contrast,
#d = [2,3,4,5,6,7,8,9,10,10,10,10,11]
def dig(lst, depth, tot)
p depth
#d.map{|e| dig(lst.dup.push(e),depth+1,tot+e)} if tot < 17
end
produces what I would expect: 0123456789999999999999888888888888
If anyone could tell me how to make the clojure output look like the ruby output, I'd appreciate it.
Thanks, John
Generally map isn't used when you don't want the returned values back and are only evaluating the sequence for side effects. Something like doseq is preferable.
(def d [2 3 4 5 6 7 8 9 10 10 10 10 11])
(defn dig1 [lst depth tot]
(print depth)
(when (< tot 17)
(doseq [i d]
(dig1 (conj lst i)
(inc depth)
(+ tot i)))))
(dig1 [0] 0 0)
Produces: 012345678999....

Processing a seq by accessing its prior elements

I want to create a sequence, however to create its every element I need access to the two previous elements. What is the generic way to do such things in clojure ?
So two slightly diff cases -
a) seq is (a b c) when I am processing c I want to have access to a and b ....
b) and having such ability to create the sequence itself by always being able to access th two previous elements.
Thanks,
Murtaza
partition gives you this nearly for free:
(partition-all 3 1 (range 100))
((0 1 2) (1 2 3) (2 3 4) (3 4 5) (4 5 6) (5 6 7) (6 7 8) ... )
then you can map your function over the sequence of partitions:
(map my-func (partition-all 3 1 (range 100)))
you just need to make your function aware of the fact that the last segment may have less than three elements if your seq is not a multiple of three. if you want to just drop any extras use partition instead of partition-all
Well, here is one way to do it. Assume you have a function g that takes the last two values as input and produces the next value.
(defn f [g x0 x1]
(let [s (g x0 x1)]
[s (fn [] (f g x1 s))]))
Given g and two consecutive values in the sequence, f returns a pair consisting of the next value and a function that will return the value after that. You can use f as follows to generate an infinite sequence of such pairs:
(iterate (fn [[v h]] (h)) (f g x0 x1))
To extract just the sequence values, do this:
(map first (iterate (fn [[v h]] (h)) (f g x0 x1)))
For example:
user=> (take 10 (map first (iterate (fn [[v h]] (h)) (f + 0 1))))
(1 2 3 5 8 13 21 34 55 89)
You can iterate using a vector of two elements and then take the first of the resulting sequence.
For example, to create the fibonacci series:
user=> (def fib (map first (iterate (fn [[a b]] [b (+ a b)]) [1 1])))
#'user/fib
user=> (take 10 fib)
(1 1 2 3 5 8 13 21 34 55)