
21 Feb
2015
21 Feb
'15
6:04 p.m.
On Sat, Feb 21, 2015 at 4:50 PM, Joel Neely
Given a list of fractional numbers, produce a smoothed list, where each value is averaged with its immediate neighbors (except the first and last, which fail to have both neighbors), as shown below.
[0.0,4.0,2.0,6.0,1.0,2.0] [ 2.0,4.0,3.0,3.0 ]
It seems natural to my eye to express this as, "A list with at least three elements contributes a value to the result", as in:
smooth :: Fractional n => [n] -> [n] smooth (a:z@(b:c:_)) = (a + b + c) / 3 : smooth z smooth _ = []
In Haskell, I would write this with higher-order functions though : smooth xs = zipWith3 (\a b c -> (a+b+c)/3) xs (drop 1 xs) (drop 2 xs) -- Jedaï