title: How to make Clojure's `while` return a value
body: <p>Can someone please explain why Clojure's <code>while</code> macro doesn't return a value? </p>
  
  <p>The <a href="http://clojuredocs.org/clojure.core/while" rel="nofollow">documentation</a> says "Presumes
  some side-effect will cause test to become false/nil." Okay, so we use <code>swap!</code> to modify the atom which is used in the test case. But can't we still have a return value (perhaps returning repeatedly, as in the case with <code>loop</code>), along <em>with</em> the side effects?</p>
  
  <p>Looking at the <a href="https://github.com/clojure/clojure/blob/clojure-1.6.0/src/clj/clojure/core.clj#L5824" rel="nofollow">source</a>, it seems like the cause could be something to do with how recursion and macros work, but I don't know enough about the internals of that to speculate.</p>
  
  <p><strong>Example</strong>:</p>
  
  <p>The following code only returns <code>nil</code>:</p>
  
  <pre><code>(let [a (atom 0)]
    (while (&lt; @a 10)
      (+ 1 @a)
      (swap! a inc)))
  </code></pre>
  
  <p>That is, it does not return the value of <code>(+ 1 @a)</code>, nor does it return any other value or function that is inside the <code>while</code> loop. If we want to get some value calculated via the <code>while</code> loop, we could use <code>print</code>, but then we can't easily use the value in some other operation. For a return value, we have to use a second atom, like this:</p>
  
  <pre><code>(let [a (atom 0)
        end (atom 0)]
    (while (&lt; @a 10)
      (swap! end #(+ 1 %))
      (swap! a inc))
    @end)
  </code></pre>