Is group-by lazy?

275 views
Skip to first unread message

Michael Jaaka

unread,
May 25, 2010, 4:23:24 AM5/25/10
to Clojure
Hi!

I've noticed that there is group-by in clojure 1.2. However it uses
reduce and conj.
Doesn't it consume all sequence at once?

Here I have lazy version I have written once:

(defn group-by
[input]
(lazy-seq
(when-let [s (seq input)]
(let [k (ffirst s) [vs r] (split-with #(-> % first (= k)) s)]
(cons [k vs] (group-by r))))))



--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Craig Andera

unread,
May 25, 2010, 8:23:31 AM5/25/10
to clo...@googlegroups.com
> I've noticed that there is group-by in clojure 1.2. However it uses
> reduce and conj.
> Doesn't it consume all sequence at once?

Yes. But then, it would have to:

-------------------------
clojure.contrib.seq/group-by
([f coll])
Returns a sorted map of the elements of coll keyed by the result of
f on each element. The value at each key will be a vector of the
corresponding elements, in the order they appeared in coll.

So let's say you did

(group-by first [[1 :a] [2 :a] [3 :a] [2 :b] [1 :b]])

You'd get

{1 [[1 :a] [1 :b]], 2 [[2 :a] [2 :b]], 3 [[3 :a]]}

And there's no way it would know about the second element in the first
entry unless it looked through the whole input collection.

> Here I have lazy version I have written once:
>
> (defn group-by
>        [input]
>          (lazy-seq
>            (when-let [s (seq input)]
>              (let [k (ffirst s) [vs r] (split-with #(-> % first (= k)) s)]
>                  (cons [k  vs] (group-by r))))))

That doesn't do the same thing as group-by. For one thing, it doesn't
take a function to produce the keys. So you might want to consider
choosing a different name.

Michael Jaaka

unread,
May 25, 2010, 9:43:51 AM5/25/10
to Clojure
Thanks you! Just noticed that after publishing that post. The clojure
1.2 group-by doesn't require sequence to be ordered by a grouping key.

My func. is easy to modify to accept grouping selector and mapping
function for grouped sequence.

Thanks again.
Reply all
Reply to author
Forward
0 new messages