Reputation: 16967
Is there a two-operand equivalent to map
built into Haskell with a type signature of:
map2 :: (a -> b -> c) -> [a] -> [b] -> [c]
The following equivalence should hold:
map2 operator as bs === [operator a b | (a, b) <- zip as bs]
Example:
ghci> map2 (*) [2,3] [4,5]
[8,15]
Upvotes: 2
Views: 449
Reputation: 12475
A more general solution is to use the ZipList
instance of Applicative
for lists:
let z = (+) <$> ZipList [2,3] <*> ZipList [4,5]
in runZipList z
The nice thing here is that it works with operators of arbitrary arity, so instead of zipWith3
.. zipWith7
, you just tack on one more <*> e
Upvotes: 1
Reputation: 19816
It's called zipWith
.
Here's its type:
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
Example:
zipWith (*) [2,3] [4,5]
Produces:
[8,15]
I might also recommend that you take a look at Hoogle for such questions in the future. A search for "(a->a->a)->[a]->[a]->[a]" turns up what you were looking for. :)
Upvotes: 6