foldl / foldr查询 [英] foldl / foldr query
问题描述
我是Haskell的初学者,甚至在阅读了foldr / foldl的几个解释之后,我无法理解为什么我会在下面得到不同的结果。什么是解释?
Prelude> foldl(\_ - >(+1))0 [1,2,3]
4
Prelude> foldr(\_->(+1))0 [1,2,3]
3
谢谢!
在 foldl
lambda传递给累加器作为第一个参数,而列表元素作为第二个参数。在 foldr
的情况下,lambda被传递给list元素作为第一个参数,而accumulator作为第二个参数。
你的lambda忽略了第一个参数,并在第二个参数中加1,所以在 foldl
情况下,你要给最后一个元素加1,并且在 foldr
的情况下,您正在计算列表中元素的数量。
I'm a beginner at Haskell, and even after reading several explanations of foldr/foldl, I can't understand why I'm getting different results below. What is the explanation?
Prelude> foldl (\_ -> (+1)) 0 [1,2,3]
4
Prelude> foldr (\_ -> (+1)) 0 [1,2,3]
3
Thanks!
In the foldl
case, the lambda is being passed the accumulator as the first argument, and the list element as the second. In the foldr
case, the lambda is being passed the list element as the first argument, and the accumulator as the second.
Your lambda ignores the first argument, and adds 1 to the second, so in the foldl
case you are adding 1 to the last element, and in the foldr
case, you are counting the number of elements in the list.
这篇关于foldl / foldr查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!