Mapping one list to another (in Haskell, + abstract solution) - 'map reduce'?
Say we have a list of coordinates like:
(1,2) (0,3) (4,1) (0,3) (-2,3) (6,5)And we wanted to result in the following list, which is defined as the summation of each consecutive coordinates. (Sorry bad definition) like so:
(1,5) (4,4) (4,4) (-2,6) (4,8)So there exists a set A = (a,b,c,...,n) where a,b,c,...,n are coordinates in R^2.
There exists a function f such that f(A) = B = (a+b,b+c,c+d,...,n-1+n).~
How would you write something like that in a functional la开发者_高级运维nguage like Haskell? A program that applies f to a given A to give B.
You can use zip
to zip the list with its tail, you get pairs of pairs like [((1,2), (0,3)), ((0,3),(4,1)), ...]
. Then you can use map
to replace each pair of pairs with its sum. Or you can use zipWith
which is basically zip
+ map
in one function, except the function given to zipWith
has type a -> b -> c
, not (a,b) -> c
:
summedCoords = zipWith (\ (a,b) (c,d) -> (a+c, b+d)) coords (tail coords)
You can write a generic function like this
g:: (a -> a -> b) -> [a] -> [b]
g f (x1:x2:xs) = (f x1 x2):(g (x2:xs))
g _ (x1:[]) = []
and pass it your add function
f = g f' where
f' (a,b) (a',b') = (a+a', b+b')
精彩评论