首页 > 解决方案 > 如何从haskell中的元组的所有第二个元素中创建一个列表

问题描述

我有一个元组列表,例如 [(1,"A"),(2,"B"),(3,"C")]

现在我想创建一个包含这些元组的所有第二个元素的列表,所以列表应该是 ["A","B","C"]

任何人都可以帮助解决这个问题吗?

标签: haskelltuples

解决方案


You can do this by running map snd [(1,"A"),(2,"B"),(3,"C")]. The map function is defined to apply the function given as its second argument to each element of the list given as its third argument; the snd function gets the second element of a tuple.

Alternatively, if you prefer list comprehensions, you could do [x | (_, x) <- [(1,"A"),(2,"B"),(3,"C")]]; this takes each element of the list, matches it to the pattern (_, x) (which assigns the second element of each tuple to x), and then returns each x.


推荐阅读