Alex Rivera | Logout

How to zip multiple lists in Haskell?

Asked 2010-03-18T07:53:18.827
22

In python zip function accepts arbitrary number of lists and zips them together.

>>> l1 = [1,2,3]
>>> l2 = [5,6,7]
>>> l3 = [7,4,8]
>>> zip(l1,l2,l3)
[(1, 5, 7), (2, 6, 4), (3, 7, 8)]
>>> 

How can I zip together multiple lists in haskell?

Edit
Report

3 Answers

11

Looks like there is also a zip3 (doc) and a zip4 (doc) function in Haskell. But the zipn seems to be complicated because of the strong type system. Here is a good discussion I've found during my research.

answered 2010-03-18T08:02:18.577
6

GHC also supports parallel list comprehensions:

{-# LANGUAGE ParallelListComp #-}

[(x,y) | x <- [1..3]
       | y <- ['a'..'c']
       ]

==> [(1,'a'),(2,'b'),(3,'c')]

I just tested it up to 26 parallel variables, which should be enough for all practical purposes.

It's a bit hacky (and non-standard) though, so in case you're writing something serious, ZipList may be the better way to go.

answered 2013-01-15T20:10:05.330
1

If all your data is of the same type you could do:

import Data.List (transpose)

zipAllWith :: ([a] -> b) -> [[a]] -> [b]
zipAllWith _ []  = []
zipAllWith f xss = map f . transpose $ xss

zipAll = zipAllWith id

Example:

> zipAll [[1, 2, 3], [4, 5, 6], [7, 8]]
[[1,4,7],[2,5,8],[3,6]]
answered 2010-03-18T16:07:51.073

Your Answer