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
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With