
On 3/25/12 8:06 AM, Michael Snoyman wrote:
A simple solution is to use the zipWith[1] function:
zipWith (+) [1,2,3] [4,5,6] == [5,7,9]
It takes a bit of time to get acquainted with all of the incredibly convenient functions in base, but once you know them, it can greatly simplify your code.
[1] http://hackage.haskell.org/packages/archive/base/4.5.0.0/doc/html/Prelude.ht...
And if you want different behavior with regards to lists of differing length, you may also be interested in pairWith[2] or zipOrWith[3] -- Silently truncate uneven lists. zipWith (+) [1,2,3] [4,5,6] == [5,7,9] zipWith (+) [1,2,3] [4,5] == [5,7] -- Give errors for uneven lists. pairWith (+) [1,2,3] [4,5,6] == Just [5,7,9] pairWith (+) [1,2,3] [4,5] == Nothing -- Assume infinitely many trailing zeros. zipOrWith plus [1,2,3] [4,5,6] == [5,7,9] zipOrWith plus [1,2,3] [4,5] == [5,7,3] where plus (Fst x ) = x plus (Snd y) = y plus (Both x y) = x+y [2] http://hackage.haskell.org/packages/archive/list-extras/0.4.0.1/doc/html/Dat... [3] http://hackage.haskell.org/packages/archive/data-or/1.0.0/doc/html/Data-Or.h... -- Live well, ~wren