如何将列表中一对的各个元素相加? [英] How do you sum the individual elements of a pair in a list?

查看:85
本文介绍了如何将列表中一对的各个元素相加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从列表中获取该对的第一个和第二个元素,以便可以对它们进行求和.这是我的代码,我不知道为什么会出错

Im trying to take the first and second element of the pair from a list so they can be summed. Here is my code, I am not sure why it is giving an error

func :: [(Double,Double)] -> (Double,Double)
func [(x, y)] = map fst (x,y)

推荐答案

首先,让我们看看您当前的非工作定义:

First, let's take your current, non-working definition:

func :: [(Double,Double)] -> (Double,Double)
func [(x, y)] = map fst (x,y)

这有几个问题:

  • 你的模式匹配 [(x, y)] 只匹配一个只有一个元素的列表.任何包含 2 个或更多元素的列表都会导致错误,因为它们不匹配.
  • map 不能应用于元组;它只能应用于列表.
  • 即使你可以 map 覆盖一个元组,fst 也必须直接应用于元组 - fst (a, b) 给出 a,而 map fst(a, b) 没有意义.
  • Your pattern match [(x, y)] only matches a list with exactly one element. Any list with 2 or more elements will cause an error since they do not match.
  • map cannot be applied to tuples; it can only be applied to lists.
  • Even if you could map over a tuple, fst must be applied to a tuple directly - fst (a, b) gives a, while map fst (a, b) doesn't make sense.

让我们看看一些替代定义.

Let's look at some alternate definitions.

func_1 :: [(Double,Double)] -> (Double,Double)
func_1 list =
    let fsts = [ a | (a, _) <- list ]
        snds = [ b | (_, b) <- list ]
    in (sum fsts, sum snds)

这会分别从列表中提取每个第一个元素,然后从列表中提取每个第二个元素,然后将它们加在一起.

This separately extracts each first element from the list, then each second element from the list, then adds them together.

func_2 :: [(Double,Double)] -> (Double,Double)
func_2 list =
    let fsts = map fst list
        snds = map snd list
    in (sum fsts, sum snds)

在输入列表的每个元素上映射 fst 以获得列表的所有第一个元素的列表.然后映射 snd 对第二个元素做同样的事情.

Maps fst over each element of the input list to get a list of all first elements of the list. Then maps snd to do the same for second elements.

func_3 :: [(Double,Double)] -> (Double,Double)
func_3 [] = (0, 0)
func_3 ((a,b) : xs) =
    let (a', b') = func_3 xs
    in (a+a', b+b')

有点不同的方法.Haskell 中的列表是递归形成的:[a, b, c] 等价于 (a : (b : (c : []))).这意味着我们可以使用模式匹配来获取列表的第一个元素以及列表的所有其他元素.此定义分为两部分:

A bit of a different approach. Lists in Haskell are formed recursively: [a, b, c] is equivalent to (a : (b : (c : []))). This means we can use pattern matching to get the first element of the list as well as all the other elements of the list. This definition works in two parts:

  • 如果列表没有元素,只需返回(0, 0)(基本情况).
  • 如果列表至少有一个元素,则取列表的其余部分(例如 [b, c] 如果给定了 [a, b, c],或 [] 如果给定了 [a]),再次使用 func_3 计算其总和,然后重新添加第一个元素.
  • If the list has no elements, just return (0, 0) (the base case).
  • If the list has at least one element, take the rest of the list (e.g. [b, c] if [a, b, c] was given, or [] if [a] was given), calculate its sum using func_3 again, then add the first element back on.

这篇关于如何将列表中一对的各个元素相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆