Nusrat
Nusrat

Reputation: 699

How to concat two lists in haskell

I have two lists x = ["a","b","c"] and y = ["Argentina","Brazil","Canada"]. I want a list of list like [["a","Argentina"],["b","Brazil"],["c","Canada"]]. Can Anyone please help me? Thanks.

Upvotes: 1

Views: 839

Answers (3)

Tom Ellis
Tom Ellis

Reputation: 9414

Without seeing your use case I would guess that tuples actually suffice, and are more type safe, hence this is just zip

x = ["a","b","c"]
y = ["Argentina","Brazil","Canada"]
z = zip x y

Prelude> z
[("a","Argentina"),("b","Brazil"),("c","Canada")]

Upvotes: 8

Zeta
Zeta

Reputation: 105876

Simply use

zipWith (\x y -> [x,y])

Upvotes: 3

Lily Ballard
Lily Ballard

Reputation: 185653

I'm not sure if there's a simpler way, but you could use zip to produce a list of tuples, and then map that back into a list of lists.

Prelude> map (\(a,b) -> [a,b]) $ zip ["a","b","c"] ["Argentina","Brazil","Canada"]
[["a","Argentina"],["b","Brazil"],["c","Canada"]]

Edit: Daniel Martin points out that zipWith is simpler.

Prelude> zipWith (\a b -> [a,b]) ["a","b","c"] ["Argentina","Brazil","Canada"]
[["a","Argentina"],["b","Brazil"],["c","Canada"]]

Upvotes: 4

Related Questions