On Tue, Dec 7, 2010 at 6:57 PM, Alan <[email protected]> wrote:
> I remember I was very excited about Java 1.5 when it came out, because
> of all the syntactic sugar it provided. I was tired of typing
>
> for (int i = 0; i < foo.length; i++) {
> Bar b = foo[i];
> // do stuff with b
> }
>
> 1.5 introduced the foreach loop syntax, so that I could instead write
>
> for (Bar b : foo)
> // do stuff with b
>
> At the time this was great, but on reflection it took a very long time
> for such a simple source-level improvement to be added to java.
> Wouldn't it be nice if I could write my own version of this instead of
> waiting for Sun to do it? In a lisp, this is trivial. Let's imagine
> that clojure had an ugly java-looking (for) syntax, instead of the
> lovely list-comprehension style it has now. Maybe it looks like this:
>
> (for i 0 (< i (.length foo)) (inc i)
> (let [bar (aget foo i)]
> (comment do stuff with bar)))
>
> And I've noticed I write the above code a lot and would like it to be
> shorter. It's not hard to write a foreach macro myself:
>
> (defmacro foreach [[name array] & body]
> `(for i# 0 (< i# (.length ~array)) (inc i#)
> (let [~name (aget ~array i#)]
> (do ~...@body))))
>
> (foreach [bar foo]
> (comment do stuff with bar))
>
> I don't know anything about Scala, but try doing this in java and
> you'll see why lisps are so powerful.
Good example; though your foreach macro evaluates array twice. I'd go with:
(defmacro foreach [[name array] & body]
`(let [a# ~array]
(for i# 0 (< i# (.length a#)) (inc i#)
(let [~name (aget a# i#)]
(do ~...@body)))))
in case the expression for the array at some call site is big and
expensive to evaluate, like (generate-prime-sieve 1e8) or something,
or, worse, has side-effects. :)
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en