我有[("m","n"),("p","q"),("r","s")].我该怎么把它转换成[["m","n"],["p","q"],["r","s"]]?
谁能帮帮我吗?谢谢.
Zet*_*eta 14
编写单个函数将一对转换为列表:
pairToList :: (a, a) -> [a]
pairToList (x,y) = [x,y]
Run Code Online (Sandbox Code Playgroud)
那你只需要map pairToList:
tuplesToList :: [(a,a)] -> [[a]]
tuplesToList = map pairToList
Run Code Online (Sandbox Code Playgroud)
或者在一行中:
map (\(x,y) -> [x,y])
Run Code Online (Sandbox Code Playgroud)
And*_*ács 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]]
Run Code Online (Sandbox Code Playgroud)
请注意,虽然lens图书馆很复杂而且对初学者不友好.