【问题标题】:What is an idiomatic way to add lists in Haskell?在 Haskell 中添加列表的惯用方法是什么?
【发布时间】:2011-01-23 21:46:07
【问题描述】:

假设我想在 Haskell 中添加两个列表。最常用的方法是什么?

这就是我所做的:

addLists :: (Integral a) => [a] -> [a] -> [a]
addLists xs ys = map add $ zip xs ys
    where add (x, y) = x+y

【问题讨论】:

  • 顺便说一句:add = uncurry (+)。另请注意,zipWith 的答案是Hoogle 查询(a -> b -> c) -> \[a\] -> \[b\] -> \[c\] 的第一个命中。
  • 感谢ehemient,下次我先试试Hoogle。
  • @TomMD,我不明白你评论的第一部分。
  • @FarmBoy:TomMD 表示(Integral a) => [a] -> [a] 是错误的。 (Integral a) => [a] -> [a] -> [a],或者更一般的(Num a) => [a] -> [a] -> [a],会是。

标签: haskell nested-lists


【解决方案1】:

有一个zipWith 库函数,它使用提供的函数组合两个列表。它完全符合您的要求,您会得到:

addLists = zipWith (+)

这使用(+) 组合作为进一步参数给出的列表元素。

【讨论】:

    【解决方案2】:

    Applicative Functor 风格:

    import Control.Applicative
    
    addLists xs ys = getZipList $ (+) <$> ZipList xs <*> ZipList ys
    

    请注意,这很丑,因为有两种方法可以使 List 成为 Applicative Functor。第一种(恕我直言,不太有用)方法是采用所有组合,这种方式成为“标准”,所以(+) &lt;$&gt; [1,2] &lt;*&gt; [30,40][31,41,32,42]。另一种方法是在此处根据需要压缩列表,但由于每种类型只能有一个类型类实例,因此我们必须将列表包装在 ZipLists 中,并使用 getZipList 解包结果。

    【讨论】:

      【解决方案3】:
      addLists xs ys = zipWith (+) xs ys
      

      【讨论】:

        猜你喜欢
        • 2011-05-04
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多