在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)
如何在foldLeft函数中输入A
到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隐含逻辑,它从类型参数Int
确定List[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 {
这就是A
中类型为foldLeft
的原因?
答案 0 :(得分:5)
foldLeft[B]
是List[A]
的成员(以及许多不同的集合类型)。所以A
只是你要折叠的集合的类型参数。
List(1, 2)
是List[Int]
,因此A = Int
。
B
是您要折叠的类型(fold
的返回类型)。它可能与A
相同,但可能不是。在您的示例中,您折叠为List[Int]
,因此B = List[Int]
(不是Int
)。
答案 1 :(得分:3)
简而言之
List(1, 2, 3).foldLeft(List[Int]())((b, a) => a :: b)
^ ^
A B