# Pairwise summation in Haskell, take two

Here's my second try at pairwise summation in Haskell:

pairwiseSum :: (Num a) => [a] -> a
pairwiseSum [] = 0
pairwiseSum [x] = x
pairwiseSum x = pairwiseSum (sumPairs x)

sumPairs :: (Num a) => [a] -> [a]
sumPairs [] = []
sumPairs [x] = [x]
sumPairs (x:y:xs) = ((x + y) : sumPairs xs)


I ran both versions on pairwiseSum (map exp [1,0.9999..(-56.0)]), and this one's noticeably faster. Is it well written?

ETA: here are some runs comparing pairwiseSum with sum :

*Main> pairwiseSum (map exp [1,0.9999..(-56.0)])
27184.177448160026
*Main> sum (map exp [1,0.9999..(-56.0)])
27184.177448147617
*Main> pairwiseSum (map exp [1,0.99999..(-56.0)])
271829.5419903211
*Main> sum (map exp [1,0.99999..(-56.0)])
271829.54198831413


The previous version of pairwiseSum gave 27184.177448160022 as the sum of the first list. On the second, I counted to 13 while pairwiseSum ran and to 11 while sum ran.

• type :set +s at GHCi and you get runtime stats with time and memory usage. But: GHCi is not the right way to test timing, take a look at criterion: hackage.haskell.org/package/criterion Apr 15, 2021 at 7:08