Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List of Tuples to List of Lists Haskell

Tags:

haskell

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.

like image 724
Nusrat Avatar asked Dec 08 '13 02:12

Nusrat


3 Answers

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])
like image 129
Zeta Avatar answered Nov 07 '22 07:11

Zeta


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.

like image 33
András Kovács Avatar answered Nov 07 '22 08:11

András Kovács


List comprehension version:

[[x,y] | (x,y) <- [("m","n"),("p","q"),("r","s")]]
like image 10
Ankur Avatar answered Nov 07 '22 07:11

Ankur