如何在Clojure中进行for循环?

Ric*_*hez 4 clojure quil

我正在学习一些Clojure,而我正在使用Quil.我想知道如何将for循环转换为Clojure:

这就是我用Java或类似语言做的事情:

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

我的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)))
Run Code Online (Sandbox Code Playgroud)

Ank*_*kur 6

您寻找的所有方法基本上都是使用序列,其中循环是关于执行特定次数的事情.Clojure提供dotimes了一定次数的事情:

(dotimes [i 10]
  (println i))
Run Code Online (Sandbox Code Playgroud)

所以你的代码就像这样:

 (dotimes [i num-sides]
   (let [pos-x (cos (* theta i))
         pos-y (sin (* theta i))]
         (ellipse pos-x pos-y poly-size poly-size)))
Run Code Online (Sandbox Code Playgroud)