foldr oddity

Joachim Breitner mail at
Wed Oct 12 09:27:35 CEST 2011

Hi Frodo,

If you happen to have a memory consumption graph somewhere on the screen
you can see that while testr does not need considerable amounts of
memory, testr' does. This can also be seen by ghci’s output.

The reason is that with testr we are building something like
True && [thunk]
which then evalutes to 
which looks at the next element in the list and evaluates to
True && [thunk]

while with testr', we start with 
[thunk] && True
and becaues && evalutes its first agument first, this thunk is entered
and we get
([thunk] && True) && True
and so on:
(([thunk] && True) && True) && True
((([thunk] && True) && True) && True) && True
until we reach the end of the list, with an inner True && True. At this
point, this chain of thunks is reduced to True

as you can see, there is much more memory stuff to do in testr' than in

If you replace && by || you’ll see that testr' behaves very similar to
the && variant, while testr finishes immediately, no matter how large
the parameter, due to the short circuiting mentioned by Daniel.


Joachim "nomeata" Breitner
  mail at  |  nomeata at  |  GPG: 0x4743206C
  xmpp: nomeata at |

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part
URL: <>

More information about the Glasgow-haskell-users mailing list