Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Why foldLeft can't work for an concat of two list?

Tags:

list

scala

fold

Defining a concat function as below with foldRight can concat list correctly

def concat[T](xs: List[T], ys: List[T]): List[T] = (xs foldRight(ys))(_ :: _)

but doing so with foldLeft

def concat1[T](xs: List[T], ys: List[T]): List[T] = (xs foldLeft(ys))(_ :: _)

results in an compilation error value :: is not a member of type parameter T, need help in understanding this difference.

EDIT :

Just in case someone might be looking for a detailed explanation on folds http://lampwww.epfl.ch/teaching/programmation_avancee/documents/programmation_avancee_5_en-2x2.pdf

like image 458
Somasundaram Sekar Avatar asked Oct 22 '14 06:10

Somasundaram Sekar


1 Answers

Arguments order in foldLeft is not the same as in foldRight.

xs.foldRight(ys){(element, aggregator) => element :: aggregator}

xs.foldLeft(ys){(aggregator, element) => element :: aggregator}

With placeholder syntax for foldLeft - (_ :: _) - you are trying to do something like this: aggregator :: element. This means element.::(aggregator) and there is no :: method in element (type of element is T).

like image 191
senia Avatar answered Sep 30 '22 06:09

senia