0

Sorry for the novice question, but I can't find the shorthand for this in Scala.

val s1 = List(8, 9, 10)
val s2 = List(7, 6, 5)
val s12 = s2.foldLeft(s1)((acc, x) => x :: acc)
assert(s12 === List(5, 6, 7, 8, 9, 10))

Which operator should I use to achieve the same effect?

BasilTomato
  • 1,071
  • 1
  • 8
  • 14

2 Answers2

6

You could reverse the 2nd list and prepend the result to the 1st list

val s12 = s2.reverse ::: s1

For additional documentation of the methods available refer to the scala.collection.immutable.List APIdocs

e.g. :::

Adds the elements of a given list in front of this list.

By the way ::: used like this (infix notation - without dot) is right-associative (it means the method will be called on the right object - s1 in this case).
Moreover, when calling ::: with dot notation, it will be called on the object left of the dot, so in this case s2.reverse.:::(s1) will result in List(8, 9, 10, 5, 6, 7)

Community
  • 1
  • 1
mucaho
  • 2,119
  • 20
  • 35
  • From what I understand that'd tad inefficient. I found `xs reverse_::: ys` which is "more efficient" according to the API docs but it sort of looks ugly.. – BasilTomato Feb 14 '15 at 20:05
  • 2
    @BasilTomato If you're talking about a small and bounded number of items, I'd choose aesthetics over performance every time. If it's a large or unbounded number of items and you're really worried about performance, you can choose a more sophisticated data structure like a `Vector` and use its `reverseIterator` to access each item in the order you want. – acjay Feb 14 '15 at 20:08
  • @BasilTomato `xs reverse_::: ys` looks interesting. Where is the API docs for it? – mucaho Feb 14 '15 at 20:08
  • @acjay: I guess, it just feels wrong to effectively reverse it twice. – BasilTomato Feb 14 '15 at 20:15
  • @mucaho: It's here -> http://www.scala-lang.org/api/current/#scala.collection.immutable.List – BasilTomato Feb 14 '15 at 20:16
  • @BasilTomato that's actually nice, I suggest you answer your own question with that variant too – mucaho Feb 14 '15 at 20:20
2

Alternatively, it can be written this way:

s2 reverse_::: s1

Which is more efficient than s2.reverse ::: s1 (this is also pointed out in the API doc).

It can also be written in this horrible way:

(s1 /: s2)(_.::(_))

On second thought, maybe s2.foldLeft(s1)((acc, x) => x :: acc) isn't that bad after all.

BasilTomato
  • 1,071
  • 1
  • 8
  • 14