On Thu, Aug 6, 2009 at 4:09 PM, Stuart
Halloway<stuart.hallo...@gmail.com> wrote:
>
> Is the following an improvement on clojure.contrib.seq-utils/
> reductions, or a step backwards?
>
> (defn my-reductions
>   ([f coll]
>      (if (seq coll)
>        (cons (first coll) (my-reductions f (first coll) (rest coll)))
>        (cons (f) nil)))
>   ([f acc coll]
>      (if (seq coll)
>        (let [nextval (f acc (first coll))]
>          (lazy-seq (cons nextval (my-reductions f nextval (rest
> coll))))))))
>
> On the plus side, it appears to be faster (as collections grow large),
> and it doesn't "cheat" by introducing an atom. On the minus side it
> isn't as pretty as the one in contrib.
>

Good call, the version in contrib predates lazy-seq and full laziness.
You can see the challenges faced in its implementation (back in the
lazy-cons days) here:

http://groups.google.com/group/clojure/browse_thread/thread/3edf6e82617e18e0/58d9e319ad92aa5f?#58d9e319ad92aa5f

But, the version you have isn't fully lazy either. As a general rule,
lazy-seq should wrap the entire body:

(defn reductions
  ([f coll]
     (lazy-seq
      (if (seq coll)
        (cons (first coll) (reductions f (first coll) (rest coll)))
        (cons (f) nil))))
  ([f acc coll]
     (lazy-seq
      (if (seq coll)
        (let [nextval (f acc (first coll))]
          (cons nextval (reductions f nextval (rest coll))))))))

Rich

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@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+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to