在 haskell 中通过列表理解提取元组的第一个元素

extracting the first element of a tuple via list comprehension in haskell

我试图通过列表理解提取 haskell 中元组列表中元组的第一个元素,但不知何故它只输出第一个然后停止,所以我决定通过递归来完成看起来像这样:

tuples :: (Ord a, Ord b) => [(a, b)] -> [a]
tuples [] = []
tuples ((x,y):xs) = x : tuples xs

现在,虽然这可行,但我想知道如何通过列表理解来做同样的事情。

是的,您可以在列表理解中使用模式匹配,其中:

tuples :: [(a, b)] -> [a]
tuples xs = [ x | <strong>(x, _)</strong> <- xs ]

但可能最简单的方法就是使用 fst :: (a, b) -> a:

tuples :: [(a, b)] -> [a]
tuples = map <b>fst</b>

(Ord a, Ord b) 的类型约束 不是 必需的:我们没有在任何地方使用为属于 Ord 类型类成员的类型定义的函数。