Scala: Why can't foldLeft work for concat from two lists?

The definition of the concat function, as shown below with the foldRight function, can be a properly ordered list

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

but with foldLeft

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

leads to a compilation error value :: is not a member of type parameter T , help is needed in understanding this difference.

EDIT:

Just in case, someone can find a detailed explanation of the folds http://lampwww.epfl.ch/teaching/programmation_avancee/documents/programmation_avancee_5_en-2x2.pdf

+5
source share
1 answer

The order of the arguments in foldLeft not the same as in foldRight .

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

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

+10
source

Source: https://habr.com/ru/post/1205255/


All Articles