为什么foldLeft的Scala实现中需要类型声明
我曾试图用以下代码在LinkedList上实现一个foldLeft,一个是Curry foldLeft2,另一个不是foldLeft:为什么foldLeft的Scala实现中需要类型声明,scala,Scala,我曾试图用以下代码在LinkedList上实现一个foldLeft,一个是Curry foldLeft2,另一个不是foldLeft: sealed trait LinkedList[+E] { @tailrec final def foldLeft[A](accumulator: A, f: (A, E) => A): A = { this match { case Node(h, t) => { val current = f(accu
sealed trait LinkedList[+E] {
@tailrec
final def foldLeft[A](accumulator: A, f: (A, E) => A): A = {
this match {
case Node(h, t) => {
val current = f(accumulator, h)
t.foldLeft(current, f)
}
case Empty => accumulator
}
}
@tailrec
final def foldLeft2[A](accumulator: A)(f: (A, E) => A): A = {
this match {
case Node(h, t) => {
val current = f(accumulator, h)
t.foldLeft2(current)(f)
}
case Empty => accumulator
}
}
}
但是当我使用foldLeft时,似乎我需要声明累加器和item的类型,但是对于foldLeft2,我不需要。有人能解释这是为什么吗
class LinkedListSpecification extends Specification {
"linked list" should {
"foldLeft correctly" in {
val original = LinkedList(1,2,3,4)
original.foldLeft(0, (acc: Int, item: Int) => acc + item) === 10
}
}
"linked list" should {
"foldLeft2 correctly" in {
val original = LinkedList(1,2,3,4)
original.foldLeft2(0)((acc, item) => acc + item) === 10
}
}
}
这是因为Scala中的类型推断在参数列表中从左到右进行。
因此,在第二个版本的
foldLeft2
中,它能够推断出类型A为Int
,然后继续下一个参数列表,在该列表中,它现在需要一个函数(Int,E)=>Int
。
而在第一个版本中,它试图同时通过两个参数(
acculator
和f
)推断A
。它抱怨您传递给它的匿名函数,因为它还没有推断出类型A
。这似乎是正确的。在第一次测试中,我能够从项中删除类型声明,并且它仍然可以编译。谢谢你的澄清。