On Thu, Nov 5, 2009 at 3:53 PM, Meikel Brandmeyer <[email protected]> wrote:
> Hi,
>
> Am 03.11.2009 um 22:41 schrieb jan:
>
> > (defn for-each [f items]
> > (when-not (empty? items)
> > (f (first items))
> > (recur f (rest items))))
>
> And to not defeat the learning exercise...
>
> (defn for-each
> [f items]
> (when-let [s (seq items)]
> (f (first s))
> (recur f (next s))))
>
(defn for-each
[f items]
(when-let [[b & r] (seq items)]
(f b)
(recur f r)))
When-let can destructure, and it short-circuits when the right-hand side of
the binding, not the result of the binding, is nil, so:
user=> (when-let [[b & r] nil] [b r])
nil
user=> (when-let [[b & r] [1]] [b r])
[1 nil]
When the input is nil, when-let short-circuits; when the input is of length
1, the rest binding is nil rather than (). Still have to pass the right hand
through (seq ...) though, if items might ever be non-nil but empty, because
e.g.
user=> (when-let [[f & r] []] [f r])
[nil nil]
rather than just nil.
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---