How to make a for loop in Clojure?

I study myself Clojure and I use Quil. I would like to know how to convert for-loop to Clojure:

Here's how I could do it in Java or similar languages:

for ( int i = 0; i < numSides; i++ ) { float posX = cos( theta * i ); float posY = sin( theta * i ); ellipse( posX, posY, polySize, polySize ); } 

My attempt to Clojure:

  (let [theta (/ PI num-sides) angle (range 0 num-sides) pos-x (cos (* theta angle)) pos-y (sin (* theta angle))] (dorun (map #(ellipse % % % %) pos-x pos-y poly-size poly-size))) 
+4
source share
4 answers

All the methods that you were looking for should mainly work with sequences, where the execution of certain actions a certain number of times is used as a loop. Clojure provide dotimes to perform certain actions for a certain number of times:

 (dotimes [i 10] (println i)) 

This way your code will become something like:

  (dotimes [i num-sides] (let [pos-x (cos (* theta i)) pos-y (sin (* theta i))] (ellipse pos-x pos-y poly-size poly-size))) 
+6
source

If you really need a C loop

 (for-loop [i 0 , (< i num-sides) , (inc i)] ... do stuff.....) 

Usually, however, I will find one of the following:

  • (dotimes [i num-sides] ....) - do something a certain number of times
  • (doseq [x some-sequence] ....) - do something for each element of the sequence
  • (for [i (range n)] ...) - create a list with n elements
+4
source

It may be somewhat academic, but I like to use Clojure "for understanding" for this kind of thing. The code will look like this:

 (dorun (for [i (range num-sides) :let [pos-x (Math/cos (* i theta)) pos-y (Math/sin (* i theta))]] (quil.core/ellipse pos-x pos-y poly-size poly-size))) 
+2
source

Doseq with range often suitable for cycling a certain number of values ​​to create side effects. I would do your loop like this:

 (doseq [i (range 0 num-sides)] (ellipse (cos (* theta i)) (sin (* theta i)) poly-size poly-size)) 
+1
source

All Articles