[英]write reverse in scala, using foldleft
here's an implementation: 这是一个实现:
def reverse[A](l: List[A]): List[A] = foldLeft(l, List[A]())((acc,h) => Cons(h,acc))
I don't understand what is inderstood by the compiler with (acc,h); 我不明白(acc,h)编译器的理解是什么; initially, the f function meets (ListA,l), which are 2 lists, so is Cons working with 2 lists also?
最初,f函数满足(ListA,l),这是2个列表,所以Cons也可以使用2个列表吗?
thanks 谢谢
Cons
works with one list and one element, just as the function passed to foldLeft
does. Cons
只能处理一个列表和一个元素,就像传递给foldLeft
的函数一样。
The declaration of foldLeft
on List[A]
is: List[A]
上的foldLeft
的声明是:
def foldLeft[B](z: B)(f: (B, A) ⇒ B): B
So we can write your impl as: 因此,我们可以将您的展示写为:
l.foldLeft(List[A]())((acc, h) => ...)
and we can see that the type B
is List[A]
, so the two arguments to our f
are acc
(of type List[A]
) and h
(of type A
). 并且我们可以看到类型
B
是List[A]
,因此f
的两个参数是acc
(类型为List[A]
)和h
(类型为A
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.