foldr oddity

Roman Cheplyaka roma at ro-che.info
Wed Oct 12 09:16:41 CEST 2011


* Daniel Peebles <pumpkingod at gmail.com> [2011-10-11 23:18:15-0400]
> Yeah, you should absolutely mind the order of the parameters (or more
> generally, when the operation isn't commutative), the strictness of the
> function's second parameter. In this case, both (&&) and (||) are strict in
> their first parameter, but both "short circuit" if the first parameter is
> False/True, and don't evaluate their second parameter. The short-circuiting
> (via laziness) terminates foldr's traversal of the entire list structure and
> saves the program lots of work. By flipping the arguments, you're basically
> forcing testr' to traverse the entire list before saying what it knew from
> the beginning.

He takes && of True's, so short-circuiting considerations should not
apply.

> On Tue, Oct 11, 2011 at 10:45 PM, Frodo Chao <frodogreat at gmail.com> wrote:
> 
> > Hi,
> >
> > I came upon this when playing with foldr and filter. Compare the two
> > definitions:
> >
> > testr  n = foldr (\x y -> x && y) True [t | (_, t) <- zip [1 .. n] [True,
> > True ..]]
> > testr' n = foldr (\x y -> y && x) True [t | (_, t) <- zip [1 .. n] [True,
> > True ..]]
> >
> > I tried these functions on ghci (The Glorious Glasgow Haskell Compilation
> > System, version 7.0.3), and get the following results (with :set +s):
> >
> > testr 1000000 => True
> > (0.01 secs, 7920832 bytes)
> > testr' 1000000 => True
> > (8.72 secs, 446585344 bytes)
> >
> > This bizarre (at least to me) behavior also applies to ||. Should I mind
> > the orderings of the parameters (especially the accumulator) in the function
> > passed to foldr?
> >
> > Thak you for reading.
> >
> > Sincerely yours,
> > Frodo Chao


-- 
Roman I. Cheplyaka :: http://ro-che.info/



More information about the Glasgow-haskell-users mailing list