简体   繁体   English

在Haskell列表中访问元组的元素

[英]Access elements of tuple in list in Haskell

I have a list of tuples, for example: 我有一个元组列表,例如:

[(1,2), (3,4), (5,6)]

Now I have to write function which sum up the first an second element of each tuple and create a list of these values. 现在,我必须编写函数,将每个元组的第一个元素和第二个元素相加并创建这些值的列表。

For the example above it should be: 对于上面的示例,应为:

[3, 7, 11]

This should be done with use of list comprehension. 这应该使用列表理解来完成。 It's not allowed to use functions like map, filter and contact. 不允许使用地图,过滤器和联系人等功能。

Any ideas how I could access the elements of the tuple in the list? 有什么想法可以访问列表中的元组元素吗?

Try this: 尝试这个:

[ x + y | (x,y) <- yourlist]

The trick is representing the two elements in a tuple from your input list as x and y and then dealing with them as needed. 技巧是将输入列表中元组中的两个元素分别表示为xy ,然后根据需要进行处理。

Let's do it without list comprehensions, using functions from the Prelude: 让我们使用Prelude中的函数在没有列表理解的情况下进行操作:

map (uncurry (+)) [(1,2), (3,4), (5,6)]

-- Result: [3, 7, 11]

How does this work? 这是如何运作的? Let's consider the types: 让我们考虑以下类型:

(+) :: Num a => a -> a -> a
uncurry :: (a -> b -> c) -> (a, b) -> c
map :: (a -> b) -> [a] -> [b]

As you may already know, in Haskell, the normal way of doing multi-argument functions is by **currying* them. 您可能已经知道,在Haskell中,执行多参数函数的常规方法是“泛滥”它们。 The type of (+) reflects this: conceptually it takes one argument and produces a function that then takes the "second" argument to produce the final result. (+)的类型反映了这一点:从概念上讲,它使用一个参数,并生成一个函数,然后使用“第二”参数来生成最终结果。

uncurry takes such a curried two-argument function and adapts it to work on a pair. uncurry采用了这样一种经过咖喱的两个参数的函数,并使它适用于一对函数。 It's trivial to implement: 实现起来很简单:

uncurry :: (a -> b -> c) -> (a, b) -> c
uncurry f (a, b) = f a b

Funnily enough, the uncurry function is curried, so its partial application uncurry (+) has type Num a => (a, a) -> a . 有趣的是,对uncurry函数进行了管理,因此其部分应用程序uncurry (+)类型为Num a => (a, a) -> a This would then be a function that takes a pair of numbers and adds them. 这将是一个接受一对数字并将其相加的函数。

And map simply applies a function to every element of a list, collecting the individual results into a list. map只是将函数应用于列表的每个元素,将各个结果收集到列表中。 Plug them all together and that's a solution. 将它们全部塞在一起,这是一个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM