On Fri, 10 Apr 2009, Chad Scherrer wrote:
A nice generalization of this that can be really useful is
movingWindow :: Int -> [a] -> [[a]]
movingWindow 1 xs = map (:[]) xs
movingWindow n xs = zipWith (:) xs . tail $ movingWindow (n-1) xs
So for example,
movingWindow 3 [1..10]
[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8],[7,8,9],[8,9,10]]
movingWindow n xs =
take (length xs - n +1) $ map (take n) $ tails xs
or more efficient using utility-ht package:
movingWindow n xs =
Data.List.Match.take (drop (n-1) xs) $
map (take n) $ tails xs
Then you can write
diff :: (Num a) => [a] -> [a]
diff = map (\[x,y] -> y - x) . movingWindow 2
Hopefully the intermediate lists are optimized away, but I haven't done any
performance testing.
I'm not sure. You are safer and more efficient when you restrict to pairs.
Since I often need the function, I defined:
http://hackage.haskell.org/packages/archive/utility-ht/0.0.4/doc/html/Data-List-HT.html#v%3AmapAdjacent
Then
diff = mapAdjacent subtract
_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe