Search code examples
scalaexceptionfoldleft

Scala: Value :: is not a member of Int


I have following Scala code sample and I want to know why I get an Error on foldLeft but not with foldRight?

val xs = List(1,2,3) 
val ys = List(4,5,6)
(xs foldLeft ys) (_::_) // Error: Value :: is not a member of Int
(xs foldRight ys) (_::_) // Res: List(1, 2, 3, 4, 5, 6)

I am new to Scala, so please reply as simple as you can. Thanks


Solution

  • The arguments for the operator (function) passed to foldLeft and foldRight are in opposite order.

    So in foldLeft your _ :: _ starts with ys :: xs.head, which doesn't make any sense.

    With foldRight, the innermost operation is xs.last :: ys, which is fine.

    The argument order makes more sense in the operator versions: z /: ws pushes z righward through ws (i.e. foldLeft), while ws :\ z pushes z leftward (i.e. foldRight). And the order of arguments inside agrees with the order of z vs. w above.