【问题标题】:Adding list of list contents to produce single list添加列表内容列表以生成单个列表
【发布时间】:2021-03-01 21:54:33
【问题描述】:

我有这个

(map . map) (\x y -> x + y) [[1,4],[2,5],[3,6]]

我希望的输出是

[5,7,9]

但是,我得到了错误

* No instance for (Show (Integer -> Integer))
         arising from a use of `print'
         (maybe you haven't applied a function to enough arguments?)
     * In a stmt of an interactive GHCi command: print it

不确定如何继续。我意识到我使用map 组合的类型是

(map . map)     :: (a -> b) ->  [[a]]  ->  [[b]]

我需要的是(a -> b) -> [[a]] -> [b],但我不确定我在哪里。

【问题讨论】:

  • 使用二元操作减少可能长列表的所有元素是foldr(或foldl',如果您的操作很严格)的域,而不是map
  • (map) (\[x, y] -> x + y) [[1,4],[2,5],[3,6]] 可以。
  • 这就是我想要的,虽然我的 lambda calc 还不能掌握它。

标签: list haskell anonymous-function


【解决方案1】:

您可以改用map sum。确实:

Prelude> map sum [[1,4], [2,5], [3,6]]
[5,7,9]

如果你使用map . map,这意味着你传递了一个函数f,这样:

(map . map) f [[x<sub>11</sub>, x<sub>12</sub>], [x<sub>21</sub>, x<sub>22</sub>], [x<sub>31</sub>, x<sub>32</sub>]]

将产生:

[[f x<sub>11</sub>, f x<sub>12</sub>], [f x<sub>21</sub>, f x<sub>22</sub>], [f x<sub>31</sub>, f x<sub>32</sub>]]

因此,您可以映射列表列表中的每个元素。但是这里你想总结各个元素,所以你使用sum :: Num a =&gt; [a] -&gt; [a]作为映射函数。

【讨论】:

  • 是的,我知道(map . map) 无法正常工作。有没有办法在匿名函数中复制sum?不挑剔,只是好奇。
  • @147pm: sum = foldr (+) 0,或者您可以使用 lambda 表达式 \x -&gt; sum x,但我不明白您为什么需要传递匿名函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-31
  • 2021-08-29
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多