"nicolas.o...@gmail.com" <nicolas.o...@gmail.com> writes:

> I doubt there is a foldr that handles the infinite list.
> To do anything, it would have to read at least one element: the last.
>
> Alex nice answer is a foldl.

Actually I think you have them backwards.  Wikipedia has a pair of
diagrams which I find very useful for visualising which is which:

foldr:
http://en.wikipedia.org/wiki/File:Right-fold-transformation.png

foldl (reduce in Clojure):
http://en.wikipedia.org/wiki/File:Left-fold-transformation.png

Look at the right side of the diagram.  That's the call structure.  (The
left side of the diagram is the linked list (1 2 3 4 5).  The ":" just
means cons in Haskell syntax.)

With a foldr the outermost call is given the first element of the list,
so mine is definitely a foldr.

Let's use (and) as the combining function and use an infinite list that
begins [true true false false ...].  So that looks like:

(lazy-foldr #(and %1 (%2)) nil (cycle [true true false false]))

We can draw an ASCII call structure diagram in the same form as the
Wikipedia one and see this:

      and
      / \
     T  and
        / \
       T  and
          / \
         F   (not evaluated)
 
Since (and) short-circuits when given false, only the part of the list
up to the first false is evaluated.

There's probably not much practical use for lazy-foldr.  But it was fun
to write. :-)

-- 
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