简体   繁体   中英

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); initially, the f function meets (ListA,l), which are 2 lists, so is Cons working with 2 lists also?

thanks

Cons works with one list and one element, just as the function passed to foldLeft does.

The declaration of foldLeft on List[A] is:

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM