[Haskell-cafe] Mapping over multiple values of a list at once?

Patai Gergely patai_gergely at fastmail.fm
Thu Aug 27 05:06:59 EDT 2009


> For example, starting from
> 
> [4,3,2,6,7]
> 
> you need to find the averages of
> 
> 4,3,2 and 3,2,6 and 2,6,7
> 
> resulting in 
> 
> [3,4,5]
> 
> What is the most elegant way to do that?
It's probably less elegant than tails, but very likely more efficient to
keep track of running sums instead of summing the sublists over and over
again.

import Data.Ratio

nsums n xs = map (% n) $ scanl (+) (sum (take n xs)) $ zipWith (-) (drop
n xs) xs

Gergely

-- 
http://www.fastmail.fm - The professional email service



More information about the Haskell-Cafe mailing list