7

I have [("m","n"),("p","q"),("r","s")]. How can I convert it to [["m","n"],["p","q"],["r","s"]]?

Can anyone please help me? Thanks.

1

3 Answers 3

19

Write a single function to convert a pair to a list:

pairToList :: (a, a) -> [a]
pairToList (x,y) = [x,y]

Then you only have to map pairToList:

tuplesToList :: [(a,a)] -> [[a]]
tuplesToList = map pairToList

Or in a single line:

map (\(x,y) -> [x,y])
Sign up to request clarification or add additional context in comments.

2 Comments

Newbie question - what's the \ for?
@AbhijitSarkar Thats just syntax for defining a lambda.
14

Using lens you can do this succinctly for arbitrary length homogenous tuples:

import Control.Lens

map (^..each) [("m","n"),("p","q"),("r","s")] -- [["m","n"],["p","q"],["r","s"]]
map (^..each) [(1, 2, 3)] -- [[1, 2, 3]]

Note though that the lens library is complex and rather beginner-unfriendly.

Comments

10

List comprehension version:

[[x,y] | (x,y) <- [("m","n"),("p","q"),("r","s")]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.