为什么在foldLeft的Scala实现中需要类型声明

时间:2015-10-14 04:26:26

标签: scala

我曾尝试使用此代码在LinkedList上实现foldLeft,一个是curried 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(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时,我似乎需要声明累加器和项目的类型,但对于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
    }
  }
}

1 个答案:

答案 0 :(得分:2)

这是因为Scala中的类型推断在参数列表中从左到右工作 因此,在第二个版本foldLeft2中,它能够在继续到下一个参数列表之前将类型A推断为Int,其中它现在需要函数(Int,E)=>Int。 在第一个版本foldLeft中,它试图通过两个参数(Aaccumulator)同时推断f。它抱怨你传递给它的匿名函数,因为它还没有推断类型A