[Haskell-cafe] adding the elements of two lists

wren ng thornton wren at freegeek.org
Mon Mar 26 04:53:47 CEST 2012


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.html#v:zipWith

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/Data-List-Extras-Pair.html#v:pairWith

[3] 
http://hackage.haskell.org/packages/archive/data-or/1.0.0/doc/html/Data-Or.html#v:zipOrWith

-- 
Live well,
~wren



More information about the Haskell-Cafe mailing list