Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Clojure bans mutation of local variables for the sake of thread safety, but it is still possible to write loops even without mutation. In each run of the loop you want to <code>my-list</code> to have a different value, but this can be achieved with recursion as well:</p> <pre><code>(let [step (fn [i my-list] (if (&lt; i 5) my-list (recur (inc i) (cons i my-list))))] (step 0 nil)) </code></pre> <p>Clojure also has a way to "just do the looping" without making a new function, namely <code>loop</code>. It looks like a <code>let</code>, but you can also jump to beginning of its body, update the bindings, and run the body again with <code>recur</code>.</p> <pre><code>(loop [i 0 my-list nil] (if (&lt; i 5) my-list (recur (inc i) (cons i my-list)))) </code></pre> <p>"Updating" parameters with a recursive tail call can look very similar to mutating a variable but there is one important difference: when you type <code>my-list</code> in your Clojure code, its meaning will always always <em>the value</em> of <code>my-list</code>. If a nested function closes over <code>my-list</code> and the loop continues to the next iteration, the nested function will always see the value that <code>my-list</code> had when the nested function was created. A local variable can always be replaced with its value, and the variable you have after making a recursive call is in a sense a different variable.</p> <p>(The Clojure compiler performs an optimization so that no extra space is needed for this "new variable": When a variable needs to be remembered its value is copied and when <code>recur</code> is called the old variable is reused.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload