为什么这个折叠不正确?

发布于 2024-11-08 01:29:15 字数 258 浏览 0 评论 0原文

我正在阅读《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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆° 2024-11-15 01:29:15

试试这个:

println( (0 /: fruit)(_ + _.length) )

传递的函数首先接收累加器(一个 Int,根据初始值 0 推断)作为参数,然后接收集合的下一个元素(一个 Int)作为参数。 >字符串,从fruit的类型推断)。

参数的顺序很容易记住,因为它们对应于初始值和集合出现的顺序。在这里,初始值首先出现,因此,累加器作为第一个参数传递 - 作为第二个参数,您将获得集合 fruit 的一个元素,该元素出现在方法名称 / 之后:。

如果您使用 foldRight 来代替,则顺序将很方便地颠倒过来:

println( (fruit :\ 0)(_.length + _) )

Try this:

println( (0 /: fruit)(_ + _.length) )

The passed function receives as argument first the accumulator (an Int, as inferred from your initial value 0) and then the next element of the collection (a String, inferred from the type of fruit).

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:

println( (fruit :\ 0)(_.length + _) )
凉城已无爱 2024-11-15 01:29:15
println( (0 /: fruit)(_ + _.length) )

传递到折叠的函数采用两个参数 (acc, elem) 的函数,其中 acc 是累加器,并且与种子 0< /code>, elem 与列表元素具有相同的类型。

如果您使用可能会更清楚:(

(0 /: fruit){ (acc, elem) => acc + elem.length }

编辑:我最初说的是元组,我已更改为两个参数的函数)

println( (0 /: fruit)(_ + _.length) )

The function to pass to the fold takes a function of two arguments (acc, elem) where acc is the accumulator and has the same type as the seed 0, elem has the same type as the elements of the list.

It may be clearer if you use:

(0 /: fruit){ (acc, elem) => acc + elem.length }

(edit: I initially said tuple, I've changed to function of two arguments)

计㈡愣 2024-11-15 01:29:15

FoldLeft(或/:)采用(作为第二个参数)一个带有两个参数的函数:
列表成员类型的累加器和变量。

所以,人们应该得到:

(0/:fruit)((acc:Int,el:String) => acc + el.length)

也就是说

(0/:fruit)(_ + _.length)

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:

(0/:fruit)((acc:Int,el:String) => acc + el.length)

which is to say

(0/:fruit)(_ + _.length)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文