How does loop work?

13 views
Skip to first unread message

slix

unread,
Jul 10, 2008, 8:08:21 PM7/10/08
to Clojure
I don't understand how loop works.

(defn lo [x]
(loop [y 0 x 1]
(pr y)))
user=> #'user/lo
user=> (lo 5)
0nil
user=>


what exactly does loop var var var var mean?

how would I do:
loop var from 1 to 20, increment by 2
print var



Sidenote: the API-reference is great but it would be even better if
there were examples. One example says more than a thousand words.
Is there a way to contribute to that?

Stephen C. Gilardi

unread,
Jul 11, 2008, 1:24:35 PM7/11/08
to clo...@googlegroups.com

On Jul 10, 2008, at 8:08 PM, slix wrote:

> I don't understand how loop works.
>
> (defn lo [x]
> (loop [y 0 x 1]
> (pr y)))
> user=> #'user/lo
> user=> (lo 5)
> 0nil
> user=>
>
>
> what exactly does loop var var var var mean?

'loop' is a binding form like 'let' that also serves as one of the
"jump to" locations for 'recur'. Your example bound y to 0 and x to 1
and then printed y.

> how would I do:
> loop var from 1 to 20, increment by 2
> print var

Here are a few of ways to accomplish the loop you gave:

(defn loop1 []
(loop [i 1]
(when (< i 20)
(pr i)
(recur (+ 2 i)))))

(defn loop2 []
(dorun (for [i (range 1 20 2)]
(pr i))))

(defn loop3 []
(doseq i (range 1 20 2)
(pr i)))

> Sdenote: the API-reference is great but it would be even better if


> there were examples. One example says more than a thousand words.
> Is there a way to contribute to that?

It's possible to contribute to that on the wiki:

http://en.wikibooks.org/wiki/Clojure_Programming#Examples

Feel free to add a new section with API examples or look around for a
place they might already fit in. I'm sure any contributions to the
wiki will be much appreciated.

--Steve

Reply all
Reply to author
Forward
0 new messages