Hi,
On Feb 10, 1:23 pm, Mark Carter <[email protected]> wrote:
> I know that loo exists - and I'm puzzled by what the lazy functions
> do.
>
> What I think would be interesting functionality is to have an emitter/
> collector combination, for example:
>
> (collect
> (doseq [ n (range 10)]
> (when (even? n) (emit n))))
>
> would return the list (0 2 4 6 8). Any ideas how I could implement
> this?
>
> You might ask why anybody would want this. Well, I think it would be
> neat because it separates your logic from actual looping mechanics.
> I'm saying "I don't care how the list is constructed, just as long as
> it is". I know there are functions like filter that would be better
> in this particular example - but I'm only using it for illustrative
> purposes.
>
> It would also allow you do do something like
>
> (collect
> (doseq [ n (range 10)]
> (when (even? n)
> (emit n)
> (emit (* 2 n)))))
>
> to give you the list (0 0 2 4 4 8 6 12 8 16). Admittedly this
> particular example might not be of much use; but the general idea is
> that it allows you to collect all sorts of weird and wonderful things,
> possibly involving complicated logic as to when/if you want things
> collection.
I don't think, what you want to do is very idiomatic for clojure. It
is more idiomatic to provide a way to obtain a seq on your data
structure and then use other means like map, to get the desired
result.
Your examples can be written as:
(mapcat #(when (even? %) [(emit %)]) (range 10))
and
(mapcat #(when (even? %) [(emit %) (emit (* 2 %))]) (range 10))
This consists can be generalised as
(defn collect-lambda
[emitter collector coll]
(mapcat (collector emitter) coll))
Again your examples:
(collect-lambda emit
(fn [emit]
(fn [n]
(when (even? n)
[(emit n)])))
(range 10))
and
(collect-lambda emit
(fn [emit]
(fn [n]
(when (even? n)
[(emit n) (emit (* 2 n))])))
(range 10))
Sincerely
Meikel
--
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