sum, perfomance?
John van Groningen
johnvg@cs.kun.nl
Tue, 6 Jun 2000 12:23:54 +0200
Igor Artelnykh wrote:
>In StdList one has
>
>sum:: !.[a] -> a | + , zero a
>sum xs = accsum zero xs
>where
> accsum n [x:xs] = accsum (n + x) xs
> accsum n [] = n
>
>
>why not
>
>sum:: !.[a] -> a | + , zero a
>sum [] = zero
>sum [x:xs] = x + sum xs
The second definition uses O(n) stack space, the first one does not because it is tail recursive.
>or even
>
>sum = foldl (+) 0
>
>Is it a perfomance issue?
Yes, when StdList was written the Clean compiler could not transform 'foldl (+) 0' into an efficient version. The current compiler can, so it could now be defined as:
sum l = foldl (+) zero l
Regards,
John van Groningen