【发布时间】:2016-01-10 12:36:59
【问题描述】:
通过“Scala 中的函数式编程”,我想知道为什么下面的代码会出现缺少参数类型的错误。
定义如下树形数据结构:
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]
还有以下方法:
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 _))
}
size2 和 maximum2 方法编译得很好,但是 depth2 不能推断最后一个函数的类型。
方法如下:
def depth2[A](t: Tree[A]): Int = fold(t)((_) => 0)((a,b) => 1 + (a max b))
让它编译得很好。
问:为什么 Scala 不能用下划线表示法推断第一种方法的类型,而用第二种方法推断类型?是什么让其他方法编译得很好?
感谢您的帮助。
scalac 版本:2.11.4
【问题讨论】:
-
another question 接受的答案也回答了这个问题。
标签: scala compilation compiler-errors functional-programming type-inference