为什么这个折叠不正确?
我正在阅读《Scala 编程》,不明白为什么这个折叠操作不正确:
val fruit = List("apples", "oranges", "lemons")
println( (0/:fruit)(_.length+_.length) )
我还尝试使用空字符串“”作为起始值 - 但也没有编译:
println( (""/:fruit)(_.length+_.length) )
I am reading Programming in Scala, and don't understand why this folding operation is not correct:
val fruit = List("apples", "oranges", "lemons")
println( (0/:fruit)(_.length+_.length) )
I also tried with empty string "" as the starting value - but that didn't compile either:
println( (""/:fruit)(_.length+_.length) )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
传递的函数首先接收累加器(一个
Int
,根据初始值0
推断)作为参数,然后接收集合的下一个元素(一个Int
)作为参数。 >字符串,从fruit
的类型推断)。参数的顺序很容易记住,因为它们对应于初始值和集合出现的顺序。在这里,初始值首先出现,因此,累加器作为第一个参数传递 - 作为第二个参数,您将获得集合
fruit
的一个元素,该元素出现在方法名称/ 之后:。
如果您使用
foldRight
来代替,则顺序将很方便地颠倒过来:Try this:
The passed function receives as argument first the accumulator (an
Int
, as inferred from your initial value0
) and then the next element of the collection (aString
, inferred from the type offruit
).The order of the arguments is easy to remember, as they correspond to the order in which the initial value and the collection appear. Here, the initial value appears first, and accordingly, the accumulator is passed as first argument — and as second argument, you get an element of the collection
fruit
, which appears after the method name/:
.If you did a
foldRight
instead, the order would be conveniently reversed:传递到折叠的函数采用两个参数
(acc, elem)
的函数,其中acc
是累加器,并且与种子0< /code>,
elem
与列表元素具有相同的类型。如果您使用可能会更清楚:(
编辑:我最初说的是元组,我已更改为两个参数的函数)
The function to pass to the fold takes a function of two arguments
(acc, elem)
whereacc
is the accumulator and has the same type as the seed0
,elem
has the same type as the elements of the list.It may be clearer if you use:
(edit: I initially said tuple, I've changed to function of two arguments)
FoldLeft(或/:)采用(作为第二个参数)一个带有两个参数的函数:
列表成员类型的累加器和变量。
所以,人们应该得到:
也就是说
foldLeft (or /:) takes (as second argument) a function which takes two arguments:
the accumulator and variable of the type of the members of the list.
So, one should get:
which is to say