efficiency question

Jorge Adriano jadrian@mat.uc.pt
Fri, 8 Feb 2002 22:50:40 +0000


On Friday 08 February 2002 22:14, you wrote:
> define
>
> test1 l =
>     let s1 = foldr (+) 1 l
>         s2 = foldr (-) 1 l
>     in  (s1, s2)
>
> test2 l =
>     let s = foldr (\x (a,b) -> (x+a,x-b)) (1,1) l
>     in  s
>
> why is test1 so much faster than test2 for long lists l (eg
> [1..1000000])?  replacing foldr with foldl makes it faster (of course),
> but test2 is still much slower.
>
> i *expected* test2 to be much faster because you're only traversing the
> list once.  presumably the two elements "a" and "b" in test2 could be put
> in registers and i'd imagine test2 should be faster (it certainly would be
> if written in c).

I'd say that's because in the second case you also got to apply the (,), 
besides the (+)/(-) constructor during the transversing...
Am I right?

J.A.