【问题标题】:How to turn a list of tuples into a single list如何将元组列表转换为单个列表
【发布时间】:2020-11-13 03:09:15
【问题描述】:

我正在尝试将一个元组列表变成一个列表,其中只有每个元组的第二个值。

targets :: [(a,b)] -> [a]
targets (x:xs) = [snd(x)] ++ targets xs

这是我到目前为止所拥有的,但它不起作用。任何帮助将不胜感激。

【问题讨论】:

  • 提示:在[(a,b)]中,第二个值的类型是b
  • 每个像这样的递归算法都需要一个终止子句,也就是说,当它不调用自己时。

标签: list haskell tuples


【解决方案1】:

您的代码中有两个错误。首先,GHC 会警告您:

<interactive>:3:30: error:
    • Couldn't match type ‘a’ with ‘b’
      ‘a’ is a rigid type variable bound by
        the type signature for:
          targets :: forall a b. [(a, b)] -> [a]
        at <interactive>:2:1-25
      ‘b’ is a rigid type variable bound by
        the type signature for:
          targets :: forall a b. [(a, b)] -> [a]
        at <interactive>:2:1-25
      Expected type: [b]
        Actual type: [a]

元组的第二个元素是b 类型(因为您将元组声明为(a, b)),所以结果数组不应该是[a](GHC 称之为实际类型),但它应该是[b](GHC 称之为预期类型)。然后,您还缺少一个案例。如果在空数组上调用它怎么办?那么它不会匹配(x:xs),所以你应该为此添加一个特殊情况(还要记住每个递归函数都应该有一个基本情况):

targets :: [(a, b)] -> [b]
-- using x:y instead of [x] ++ y since they do the same thing
targets (x:xs) = snd x:targets xs
-- the base case for when nothing matches
targets _ = []

【讨论】:

    【解决方案2】:

    这是一个 映射,其中对于每个 2 元组,您获取第二个元素,因此我们可以使用 map :: (a -&gt; b) -&gt; [a] -&gt; [b]

    targets :: [(a,b)] -> [b]
    targets = map snd

    注意返回类型是[b]bs 的列表,而不是as。但是,Graph 的类型为 [(Node a, [Int])],因此您需要将这些列表连接在一起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 2014-06-10
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      相关资源
      最近更新 更多