Tomahawk
Tomahawk

Reputation: 11

how to match list elements 1-to-1 in Haskell

I have 2 lists in equal number of elements e.g.: [1,2,3] and ['a','b','c'].

I want to merge both of them in the format [(1,'a')(2,'b')(3,'c')]. Is it possible? If so, how to do that? I couldn't find a way.

Upvotes: 0

Views: 100

Answers (2)

AJF
AJF

Reputation: 11923

There are three main ways of doing this.

First, the zip function:

> zip [1,2,3] "abc"
[(1,'a'), (2,'b'), (3, 'c)]

And it's pal, the zipWith function:

> zipWith (,) [1,2,3] "abc"
[(1,'a'), (2,'b'), (3, 'c)]

Finally, with the ParallelListComp extension*:

> [(a,b) | a <- [1,2,3] | b <- "abc"]
[(1,'a'),(2,'b'),(3,'c')]

If you're looking for a function in the future, use hoogle, which lets you look for type signatures as well as names.


If you really want to, you can define it explicitly:

zip' :: [a] -> [b] -> [(a,b)]
zip' []     _      = []
zip' _      []     = []
zip' (a:as) (b:bs) = (a,b) : zip as bs

*call GHCi with -XParallelListComp or add {-# OPTIONS_GHC -XParallelListComp #-} to your file.

Upvotes: 0

bheklilr
bheklilr

Reputation: 54068

You're looking for the zip function:

> zip [1, 2, 3] ['a', 'b', 'c']

For future reference you can use hoogle to help find functions based on their type signature.

Upvotes: 5

Related Questions