【发布时间】:2015-02-13 16:54:53
【问题描述】:
在这个 foldLeft 的定义中,Ints 的列表被颠倒了:
val l = List(1, 2) //> l : List[Int] = List(1, 2)
l.foldLeft(List[Int]())((b, a) => a :: b) //> res2: List[Int] = List(2, 1)
A 如何在 foldLeft 函数中输入 Int?
foldLeft 的来源是:
def foldLeft[B](z: B)(f: (B, A) => B): B = {
var acc = z
var these = this
while (!these.isEmpty) {
acc = f(acc, these.head)
these = these.tail
}
acc
}
什么决定了A 类型?是否有一些 Scala 隐式逻辑从类型参数 List[Int] 确定 Int 类型?
更新:
foldLeft 在 LinearSeqOptimized 中定义。
当使用val l = List(1,2) 创建列表时,这也将A 参数键入到LinearSeqOptimized,因为它是其对象层次结构的一部分:
sealed abstract class List[+A] extends AbstractSeq[A]
with LinearSeq[A]
with Product
with GenericTraversableTemplate[A, List]
with LinearSeqOptimized[A, List[A]]
with Serializable {
这就是为什么在 foldLeft 中将类型 A 键入 Int 的原因?
【问题讨论】:
-
A是列表元素类型。 -
如果我们在类型级别和值级别进行命名一样谨慎,不是很好吗?
-
@acjay 同意,但是类型的单字符变量名称使得从这些名称中提取含义更加困难,我认为这可能会导致错误。
标签: scala