The code below draws me the sine wave throughout the screen, and beyond.
However, I want that x never exceeds (width). At that point, the window should be cleared, and the wave should be drawn again, starting at 0. I tried
(set-state! :x (mod (seq->stream x) (width)))
but it didn't work. I checked some examples, tried some code which made use of checking whether (> x (width)), tried to put the logic into the draw function, but they don't work either.
I would like to draw a continuous waveform (like an electrocardiogram) on a limited display. I would appreciate any help.
(ns soso.core
(:require [quil.core :refer :all]
[quil.helpers.seqs :refer [seq->stream range-incl]]))
(defn setup []
(smooth)
(frame-rate 100)
(background 255)
(let [x (range-incl)]
(set-state! :x (seq->stream x))))
(defn draw []
(stroke 0)
(stroke-weight 2)
(let [x ((state :x))
y (round (* 100 (abs (sin x))))]
(ellipse x y 4 4)))
Edit
When I tried to put the logic into the draw function, I wrote (set-state! :x 0) in the setup function, and put the following code into the draw function:
(let [x (if (> ((state :x)) 10)
0
(inc ((state :x))))])
But it didn't work, and didn't throw any error in any of the nrepl buffers. To see what happened, I tried this code in the user repl:
(let [x 0]
(take 20
(if (> x 10)
0
(inc x))))
Even if I tried this code by wrapping the if statement inside (into '()), the code complained with: "IllegalArgumentException Don't know how to create ISeq from: java.lang.Long clojure.lang.RT.seqFrom". It is the same with:
(loop [x 0]
(if (> x 10)
0
(recur (inc x))))
What is wrong with this if statement? The clojure api says that if tests the test condition, and then evaluates and yields then or else branches, accordingly. If it yields, it should spit out that integer, which in turn gets added to the list, which in turn should be listed by take function, I think.
Something more like this seems to give the effect you are looking for.
(defn draw []
(stroke 0)
(stroke-weight 2)
(let [x ((state :x))
y (+ 100 (* 100 (sin (/ x 100))))]
(ellipse (mod x (width)) y 4 4)))
Couple of issues you are encountering:
The input to sin is a floating value in radians. My hackery of divide by 100 here just makes sure that we're getting a nice continuous output. Practically if you want to cycle every n pixels you need to use 2 PI / n to adjust x.
Rounding off the value is going to give you points, as the domain of sin is 1 to -1. Here I'm adjusting by adding on 100.
Where you fiddle with x will depend on the exact requirement. Here I'm simply wrapping your x value by taking it's modulus in the draw function.
Hope this helps.
Related
I have a simple function that adds numbers together and multiplies them.
(defn add-and-multiply [x y z]
(let [add (+ x y z)
mult (* x y z)]
(println "Add: " add)
(println "Mult: " mult)))
(add-and-multiply 1 1 2)
Add: 4
Mult: 2
nil
How would I call add-and-multiply again with the x argument now being the result of add (4), the y argument being the result of mult (2) and the z argument being the same (2).
How could I then repeat this process 100 times and then print the final values of add and mult?
Any help would be much appreciated. Thanks
I would not be surprised to find that the result after 100 iterations is too large to fit into RAM. Unless I am misunderstanding the formula, this is a lot like computing x*(x^2)*(x^4)*(x^8)...up to x^(2^100), which simplifies to x^(2^200). It's actually larger because there is an adding step as well, but I think that is relatively minor compared to the iterative multiplication. 2^200 is pretty big already, but you could compute it if you needed to.
However, 2^(2^200) is tremendously vast. Obviously you need 2^200 bits of RAM, at a minimum, to hold that number without losing precision. A typical desktop computer has perhaps 16GB of RAM, which is 2^30 (a billion) * 16 gigs * 8 bits/byte = 2^37 bits of storage. You would need not just one desktop computer to store this, but 2^163 of them. Again, I cannot emphasize enough just how large a number that is. If every grain of sand on the planet were a desktop computer with 16GB of RAM, you would not be close to being able to store this number.
So, I would say you should probably figure out a different way to solve whatever your real problem is, assuming you can't afford to buy whole galaxies worth of computing power.
That said, regarding the mechanics of how to generalize (f (f (f (f x)))) to an arbitrary number of calls to f, the other answers have given you a good explanation of how to use iterate, and will serve you well if you choose an f whose runtime is more manageable.
If you change add-and-multiply to return the two results:
(defn add-and-multiply [x y z]
(let [add (+ x y z)
mult (* x y z)]
[add mult]))
then you can use iterate to generate successive applications. Use first and drop to select the result you want e.g.
(first (drop 10 (iterate (fn [[x y]] (add-and-multiply x y 2)) [(bigint 1) (bigint 2)])))
;; have a look at juxt
((juxt + * (fn [_ _ x] x)) 1 1 2) [4 2 2]
;; you can then use it like this:
(second (iterate (fn [v]
(apply (juxt + * (fn [_ _ x] x)) v)) [1 1 2])) ;; [4 2 2]
;; however it overflows quickly, so use +' *'
;; also, put it into a function
(defn add-and-multiply [times nb]
(nth (iterate (fn [v]
(apply (juxt +' *' (fn [_ _ x] x)) v)) nb) times))
(add-and-multiply 10 [1 1 2]) ;; [7983075120467448500799760620188561621081118348584N 20456985749705433596250191236583540578087736309004220218432871989995224183078912N 2]
A concise way to do this is
(defn compute [n]
(let [step (fn [[x y z :as all]] [(reduce +' all) (reduce *' all) z])]
(nth (iterate step [1 1 2]) n)))
This runs out of steam on my laptop at about n = 35.
Spelling out the computation helps a little:
(defn compute [n]
(loop [x 1, y 1, z 2, n n]
(if (zero? n)
[x y z]
(recur (+' x y z) (*' x y z) z (dec n)))))
But life is too short to wait for either of these to compute the result for n = 100.
We could pull z out of the computation either way, since it stays constant at 2. It doesn't save much to do so, so I chose to stay with the question's prescription.
(defn prime [x]
(if (#(<= % (Math/sqrt x)) (first (filter zero? (mod x (range 2 (inc x))))))
false
true))
Hi there! I want to check the given number is prime or not using clojure. Firstly, I want to filter all the divisors of x, then select the first number of these divisors. Finally, comparing to the square root of x, if the first divisor is smaller or equal to x, then the given number is not a prime. Otherwise, it is. However, when I run the code, I got such an error. How can I figure out the problem that convert a Lazyseq to a Number? I would appreciate if anyone can help me!
I think the problem is slightly different. We do not want to try values greater than the square root of the number we want to know is prime or not. Reason is explain in this SO. (Basically if x = a * b, then both a AND b cannot be greater than the square root)
So the sequence we are building, is up to the square root
(defn root-1 [x]
(inc (long (Math/sqrt x))))
(defn range-1 [x]
(range 2 (root-1 x)))
Finally, we are filtering on divisor:
(defn filter-1 [x]
(filter #(zero? (rem x %))
(range-1 x)))
And especially, we can stop at the first one, and filter being lazy, that comes up nicely with:
(defn is-prime [x]
(nil? (first (filter-1 x))))
Which we can try with:
(is-prime 10) ; false
(is-prime 11) ; true
Fast check that number is prime:
(ns example.core
(:gen-class)
(:require [clojure.core.reducers :as r]))
(defn prime-number?
[n]
(let [square-root (Math/sqrt n)
mod-zero? (fn [res new-val]
(if (zero? (mod n new-val))
(reduced false)
true))]
(r/reduce mod-zero? true (range 2 (inc square-root)))))
(prime-number? 2147483647)
;=> true
Two comments:
range returns a seq, which you are trying to apply (mod x ...) to. I think you are missing a map..
There is no real point in returning true and false from an if, if you think about it ;) (hint, try to see how the function not behaves)
You should make another attempt and update us on what you came up with!
Paraphrasing your recipe:
Filter all the divisors of x.
Select the first of these.
If it is smaller then or equal to the square root of x, then x
is not a prime.
The given code has the problems:
The surrounding if form is redundant.
The filter function is wrong. It ought to incorporate the zero? and
the mod x.
There is no need to construct and apply an anonymous function. Just
apply the test directly.
And, though the repaired algorithm would work, it is still clumsy.
The first divisor of a prime x is x itself. There is no need to
muck about with square roots.
The range ought to be from 2 to the square root of x. Then a nil
value for the first divisor indicates a prime.
This is one of those "Is there a built-in/better/idiomatic/clever way to do this?" questions.
I want a function--call it fn-pow--that will apply a function f to the result of applying f to an argument, then apply it to the result of applying it to its result, etc., n times. For example,
(fn-pow inc 0 3)
would be equivalent to
(inc (inc (inc 0)))
It's easy to do this with iterate:
(defn fn-pow-0
[f x n]
(nth (iterate f x) n))
but that creates and throws away an unnecessary lazy sequence.
It's not hard to write the function from scratch. Here is one version:
(defn fn-pow-1
[f x n]
(if (> n 0)
(recur f (f x) (dec n))
x))
I found this to be almost twice as fast as fn-pow-0, using Criterium on (fn-pow inc 0 10000000).
I don't consider the definition of fn-pow-1 to be unidiomatic, but fn-pow seems like something that might be a standard built-in function, or there may be some simple way to define it with a couple of higher-order functions in a clever arrangement. I haven't succeeded in discovering either. Am I missing something?
The built-in you are looking for is probably dotimes. I'll tell you why in a round-about fashion.
Time
What you are testing in your benchmark is mainly the overhead of a level of indirection. That (nth (iterate ...) n) is only twice as slow as what compiles to a loop when the body is a very fast function is rather surprising/encouraging. If f is a more costly function, the importance of that overhead diminishes. (Of course if your f is low-level and fast, then you should use a low-level loop construct.)
Say your function takes ~ 1 ms instead
(defn my-inc [x] (Thread/sleep 1) (inc x))
Then both of these will take about 1 second -- the difference is around 2% rather than 100%.
(bench (fn-pow-0 my-inc 0 1000))
(bench (fn-pow-1 my-inc 0 1000))
Space
The other concern is that iterate is creating an unnecessary sequence. But, if you are not holding onto the head, just doing an nth, then you aren't really creating a sequence per se but sequentially creating, using, and discarding LazySeq objects. In other words, you are using a constant amount of space, though generating garbage in proportion to n. However, unless your f is primitive or mutating its argument, then it is already producing garbage in proportion to n in producing its own intermediate results.
Reducing Garbage
An interesting compromise between fn-pow-0 and fn-pow-1 would be
(defn fn-pow-2 [f x n] (reduce (fn [x _] (f x)) x (range n)))
Since range objects know how to intelligently reduce themselves, this does not create additional garbage in proportion to n. It boils down to a loop as well. This is the reduce method of range:
public Object reduce(IFn f, Object start) {
Object ret = f.invoke(start,n);
for(int x = n+1;x < end;x++)
ret = f.invoke(ret, x);
return ret;
}
This was actually the fastest of the three (before adding primitive type-hints on n in the recur version, that is) with the slowed down my-inc.
Mutation
If you are iterating a function potentially expensive in time or space, such as matrix operations, then you may very well be wanting to use (in a contained manner) an f that mutates its argument to eliminate the garbage overhead. Since mutation is a side effect, and you want that side effect n times, dotimes is the natural choice.
For the sake of example, I'll use an atom as a stand-in, but imagine bashing on a mutable matrix instead.
(def my-x (atom 0))
(defn my-inc! [x] (Thread/sleep 1) (swap! x inc))
(defn fn-pow-3! [f! x n] (dotimes [i n] (f! x)))
That sounds just like composing functions n times.
(defn fn-pow [f p t]
((apply comp (repeat t f)) p))
Hmmm. I note that Ankur's version is around 10x slower than your original - possibly not the intent, no matter how idiomatic? :-)
Type hinting fn-pow-1 simply for the counter yields substantially faster results for me - around 3x faster.
(defn fn-pow-3 [f x ^long n]
(if (> n 0)
(recur f (f x) (dec n))
x))
This is around twice as slow as a version which uses inc directly, losing the variability (not hinting x to keep to the spirit of the test)...
(defn inc-pow [x ^long n]
(if (> n 0)
(recur (inc x) (dec n))
x))
I think that for any nontrivial f that fn-pow-3 is probably the best solution.
I haven't found a particularly "idiomatic" way of doing this as it does not feel like common use case outside of micro benchmarks (although would love to be contradicted).
Would be intrigued to hear of a real world example, if you have one?
To us benighted imperative programmers, a more general pattern is known as a while statement. We can capture it in a macro:
(defmacro while [bv ; binding vector
tf ; test form
recf ; recur form
retf ; return form
]
`(loop ~bv (if ~tf (recur ~#recf) ~retf)))
... in your case
(while [x 0, n 3] (pos? n)
[(inc x) (dec n)]
x)
; 3
I was hoping to type-hint the n, but it's illegal. Maybe it's
inferred.
Forgive me (re)using while.
This isn't quite right: it doesn't allow for computation prior to the recur-form.
We can adapt the macro to do things prior to the recur:
(defmacro while [bv ; binding vector
tf ; test form
bodyf ; body form
retf ; return form
]
(let [bodyf (vec bodyf)
recf (peek bodyf)
bodyf (seq (conj (pop bodyf) (cons `recur recf)))]
`(loop ~bv (if ~tf ~bodyf ~retf))))
For example
(while [x 0, n 3] (pos? n)
(let [x- (inc x) n- (dec n)] [x- n-])
x)
; 3
I find this quite expressive. YMMV.
I am in the progress of learning clojure after work and I'm doing this by making a small game (loving the quil library) to make me familiar with the different aspects of clojure in specific and FP in general.
So, my game world exists of 3d grid of map data strucutures (vector of a vector of a vector of a map). I want to itterate over every point in 3d space (map) and change the data when a condition is met. This was my initial solution:
(the game data structure is the game state (a map))
(defn soil-gen [game]
(let [world-x (game :world-x)
world-y (game :world-y)
world-z (game :world-z)]
(for [x (range world-x)
y (range world-y)
z (range world-z)
:when (> z (* world-z (rand)))]
(assoc-in game [:world x y z :type] :soil))))
But this returns a list of the results (my game state data structure) of every iteration instead of one game data structure. I should somehow be able to pass the result of each iteration back to for. Something like loop/recur probably but I think you cant combine recur with for.
Somebody a clue?
thanks
What you can do is use reduce with for as shown below:
(defn soil-gen [game]
(let [world-x (game :world-x)
world-y (game :world-y)
world-z (game :world-z)]
(reduce (fn [g [x y z]] (assoc-in g [:world x y z :type] :soil)))
game
(for [x (range world-x)
y (range world-y)
z (range world-z)
:when (> z (* world-z (rand)))]
[x y z]))))
You probably want to use something like reduce to pass the accumulated result between each iteration.
Simplified examples:
(reduce
(fn [m val] (assoc m val (str "foo" val)))
{} ;; initial value for m
(range 5)) ;; seqence of items to reduce over
=> {4 "foo4", 3 "foo3", 2 "foo2", 1 "foo1", 0 "foo0"}
reduce is generally very useful whenever so have some concept of an "accumulated value" in functional programming. It also has the advantage of being very efficient.
I'm doing Project Euler to learn Clojure.
The purpose of this function is to calculate the lcm of the set of integers from 1 to m.
(lcm 10) returns 2520
This is a rather brute-force way of doing this. In theory, we go through each number from m to infinity and return the first number for which all values 1 through m divide that number evenly.
If I understand what 'lazy' means correctly (and if I am truly being lazy here), then this should run in constant space. There's no need to hold more than the list of numbers from 1 to m and 1 value from the infinite set of numbers that we're looping through.
I am, however, getting a java.lang.OutOfMemoryError: Java heap space at m values greater than 17.
(defn lcm [m]
(let [xs (range 1 (+ m 1))]
(first (for [x (iterate inc m) :when
(empty?
(filter (fn [y] (not (factor-of? y x))) xs))] x))))
Thanks!
As far as I can tell, your code is in fact lazy (also in the sense that it's in no hurry to reach the answer... ;-) -- see below), however it generates piles upon piles upon piles of garbage. Just consider that (lvm 17) amounts to asking for over 1.2 million lazy filtering operations on (range 1 18). I can't reproduce your out-of-memory problem, but I'd tentatively conjecture it might be an issue with your memory & GC settings.
Now although I realise that your question is not actually about algorithms, note that the production of all that garbage, the carrying out of all those filtering operations etc. not only utterly destroy the space complexity of this, but the time complexity as well. Why not use an actual LCM algorithm? Like the one exploiting lcm(X) = gcd(X) / product(X) for X a set of natural numbers. The GCD can be calculated with Euclid's algorithm.
(defn gcd
([x y]
(cond (zero? x) y
(< y x) (recur y x)
:else (recur x (rem y x))))
([x y & zs]
(reduce gcd (gcd x y) zs)))
(defn lcm
([x y] (/ (* x y) (gcd x y)))
([x y & zs]
(reduce lcm (lcm x y) zs)))
With the above in place, (apply lcm (range 1 18)) will give you your answer in short order.
I'm getting the same OutOfMemoryError on Clojure 1.1, but not on 1.2.
I imagine it's a bug in 1.1 where for holds on to more garbage than necessary.
So I suppose the fix is to upgrade Clojure. Or to use Michal's algorithm for an answer in a fraction of the time.
While I accept that this is acknowledged to be brute force, I shiver at the idea. For the set of consecutive numbers that runs up to 50, the lcm is 3099044504245996706400. Do you really want a loop that tests every number up to that point to identify the lcm of the set?
Other schemes would seem far better. For example, factor each member of the sequence, then simply count the maximum number of occurrences of each prime factor. Or, build a simple prime sieve, that simultaneously factors the set of numbers, while allowing you to count factor multiplicities.
These schemes can be written to be highly efficient. Or you can use brute force. The latter seems silly here.
Michal is correct about the problem. A sieve will be a little bit faster, since no gcd calculations are needed:
EDIT: This code is actually horribly wrong. I've left it here to remind myself to check my work twice if I have such a hangover.
(ns euler (:use clojure.contrib.math))
(defn sieve
([m] (sieve m (vec (repeat (+ 1 m) true)) 2))
([m sieve-vector factor]
(if (< factor m)
(if (sieve-vector factor)
(recur m
(reduce #(assoc %1 %2 false)
sieve-vector
(range (* 2 factor) (+ 1 m) factor))
(inc factor))
(recur m sieve-vector (inc factor)))
sieve-vector)))
(defn primes [m] (map key (filter val (seq (zipmap (range 2 m) (subvec (sieve m) 2))))))
(defn prime-Powers-LCM [m] (zipmap (primes m) (map #(quot m %) (primes m))))
(defn LCM [m] (reduce #(* %1 (expt (key %2) (val %2))) 1 (seq (prime-Powers-LCM m))))