Working through "Functional programming in Scala", I was wondering why the following code gives a missing parameter type error.
Defined is the following tree data structure:
sealed trait Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
And the following methods:
object Tree {
def fold[A,B](t: Tree[A])(z: A => B)(f: (B,B) => B): B = t match {
case Leaf(v) => z(v)
case Branch(l,r) => f(fold(l)(z)(f), fold(r)(z)(f)) }
def size2[A](t: Tree[A]): Int = fold(t)((_) => 1)(_ + _ + 1)
def maximum2(t: Tree[Int]): Int = fold(t)((a) => a)(_ max _)
def depth2[A](t: Tree[A]): Int = fold(t)((_) => 0)(1 + (_ max _))
}
The methods size2 and maximum2 compile just fine, but depth2 does not infer the types on the last function.
Writing the method like:
def depth2[A](t: Tree[A]): Int = fold(t)((_) => 0)((a,b) => 1 + (a max b))
makes it compile just fine.
Q: Why isn't Scala able to infer the type on the first method with the underscore notation, but is on the second method? And what makes the other methods compile just fine?
Thanks for your help.
scalac version: 2.11.4