Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a for-loop in Clojure?

Tags:

clojure

quil

I'm learning myself some Clojure and I'm using Quil. I would like to know how to translate a for-loop into Clojure:

This is how I would 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 Clojure attempt:

  (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)))
like image 352
Ricardo Sanchez Avatar asked Dec 09 '22 17:12

Ricardo Sanchez


2 Answers

All the ways that you have looked for are basically to work with sequences where as a loop is about executing things for a specific number of times. Clojure provide dotimes to do things for certain number of times:

(dotimes [i 10]
  (println i))

So your code becomes 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)))
like image 156
Ankur Avatar answered Dec 11 '22 11:12

Ankur


If you genuinely want an C-style for loop, then my clojure-utils libray has a handy for-loop macro that lets you do stuff like:

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

Normally however, I will find myself using one of the following:

  • (dotimes [i num-sides] ....) - do something a specific number of times
  • (doseq [x some-sequence] ....) - do something for every element in a sequence
  • (for [i (range n)] ...) - constructing a list with n elements
like image 40
mikera Avatar answered Dec 11 '22 10:12

mikera