foldr oddity

Joachim Breitner mail at joachim-breitner.de
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 
[thunk]
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
testr.


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.

Greetings,
Joachim

-- 
Joachim "nomeata" Breitner
  mail at joachim-breitner.de  |  nomeata at debian.org  |  GPG: 0x4743206C
  xmpp: nomeata at joachim-breitner.de | http://www.joachim-breitner.de/

-------------- 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: <http://www.haskell.org/pipermail/glasgow-haskell-users/attachments/20111012/78520472/attachment.pgp>


More information about the Glasgow-haskell-users mailing list