Search code examples
listscalafoldleft

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


Solution

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