Convert List of Tuples to List of Lists Haskell

女生的网名这么多〃 提交于 2021-01-22 07:36:43

问题


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:


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])



回答2:


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.




回答3:


List comprehension version:

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


来源:https://stackoverflow.com/questions/20449231/convert-list-of-tuples-to-list-of-lists-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!