List 添加列表内容列表以生成单个列表
我有这个List 添加列表内容列表以生成单个列表,list,haskell,anonymous-function,List,Haskell,Anonymous Function,我有这个 (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
(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]
,但我不确定我在哪里。你可以用映射求和
。事实上:
Prelude> map sum [[1,4], [2,5], [3,6]]
[5,7,9]
将产生:
[[f x11, f x12], [f x21, f x22], [f x31, f x32]]
[[fx11,fx12],[fx21,fx22],[fx31,fx32]]
因此,您可以映射列表列表中的每个元素。但是在这里,您希望对各个元素求和,因此使用as-mapping函数。您可以使用
map-sum
。事实上:
Prelude> map sum [[1,4], [2,5], [3,6]]
[5,7,9]
将产生:
[[f x11, f x12], [f x21, f x22], [f x31, f x32]]
[[fx11,fx12],[fx21,fx22],[fx31,fx32]]
因此,您可以映射列表列表中的每个元素。但是在这里,您想对单个元素进行汇总,因此使用映射函数。使用二进制操作减少潜在长列表中的所有元素是
foldr
(或者foldl'
,如果您的操作是严格的),而不是map
(map)(\[x,y]>x+y)[[1,4],[2,5],[3,6]]会起作用。这就是我一直在寻找的,尽管我的lambda计算程序还不能掌握它。使用二进制操作减少潜在长列表中的所有元素是foldr
(或者foldl'
,如果操作严格的话),而不是map
(map)(\[x,y]>x+y)[[1,4],[2,5],[3,6]]
会起作用。这就是我一直在寻找的,尽管我的lambda计算器还不能掌握它。是的,我知道(map.map)
不会起作用。在匿名函数中是否无法复制sum
?不重要,只是好奇。@147pm:sum=foldr(+)0
,或者您可以使用lambda表达式\x->sum x
,但我不明白您为什么需要传递匿名函数。是的,我知道(map.map)
将无法工作。在匿名函数中是否无法复制sum
?不重要,只是好奇。@147pm:sum=foldr(+)0
,或者您可以使用lambda表达式\x->sum x
,但我不明白您为什么需要传递匿名函数。