我有[("m","n"),("p","q"),("r","s")]
。如何将其转换为[["m","n"],["p","q"],["r","s"]]
?
任何人都可以帮助我吗?感谢。
答案 0 :(得分:14)
编写单个函数将一对转换为列表:
pairToList :: (a, a) -> [a]
pairToList (x,y) = [x,y]
然后您只需要map
pairToList
:
tuplesToList :: [(a,a)] -> [[a]]
tuplesToList = map pairToList
或者在一行中:
map (\(x,y) -> [x,y])
答案 1 :(得分:10)
使用lens
,你可以简洁地为任意长度的同质元组做到这一点:
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]]
请注意,lens
库很复杂,而且初学者不友好。
答案 2 :(得分:8)
列表理解版本:
[[x,y] | (x,y) <- [("m","n"),("p","q"),("r","s")]]