问题
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