How to interpret scaladoc?

How does foldRight[B](B)scaladoc match the actual callfoldRight(0)

args is an array of integers in a string representation

val elems = args map Integer.parseInt
elems.foldRight(0) (_ + _)

Scaladoc says:

scala.Iterable.foldRight[B](B)((A, B) => B) : B
Combines the elements of this list together using the binary function f, from right to left, and starting with the value z. 

@note Will not terminate for infinite-sized collections. 

@return f(a0, f(a1, f(..., f(an, z)...))) if the list is [a0, a1, ..., an]. 

And it’s not very important, what do the periods after f (an, z) mean?

+3
source share
2 answers

As Steve said that "..." is just an ellipsis, which indicates a variable number of parameters that are not displayed.

Go to Scaladoc and show it step by step:

def foldRight[B](z: B)(op: (B, A) β‡’ B): B

This is not significant enough. What is A? This is defined in the class Iterable(or any other class for which it is defined for):

trait Iterable[+A] extends AnyRef // Scala 2.7
trait Iterable[+A] extends Traversable[A] with GenericTraversableTemplate[A, Iterable[A][A]] with IterableLike[A, Iterable[A]] // scala 2.8

, A - . A Int:

val elems = args map Integer.parseInt

, [B]. . , , , :

elems.foldRight(0) (_ + _)
elems.foldRight[Int](0) (_ + _)

0L 0, B Long. "" 0, B String. , .

, B - Int, z - 0. , . , . , ([B]). , , , . :

val elemsFolder: ((Int, Int) => Int) => Int = elems.foldRight(0)

:

elemsFolder(_ + _)

, op, , , (B, A) => B. , , , : , z, - , , - , . A B Int, (Int, Int) => Int. "", (String, Int) => String.

, B, , z, , foldRight.

foldRight, :

def foldRight[B](z: B)(op: (B, A) => B): B = {
  var acc: B = z
  var it = this.reverse.elements // this.reverse.iterator on Scala 2.8
  while (!it.isEmpty) {
    acc = op(acc, it.next)
  }
  return acc
}

, , .

+6

Everything you need to know about foldLeftand foldRightcan be learned from the following:

scala> List("1", "2", "3").foldRight("0"){(a, b) => "f(" + a + ", " + b + ")"}  
res21: java.lang.String = f(1, f(2, f(3, 0)))

scala> List("1", "2", "3").foldLeft("0"){(a, b) => "f(" + a + ", " + b + ")"} 
res22: java.lang.String = f(f(f(0, 1), 2), 3)
+5
source

Source: https://habr.com/ru/post/1736394/


All Articles