Example: List(red,blue,green,black).I want to append head of this list to the tail of same list.So after first iteration my list will be List(blue,green,black,red),after that List(green,black,red,blue) and so on.
Asked
Active
Viewed 635 times
1 Answers
2
The first thing it comes to my mind is do what you are just saying, append the head of the list to the tail
val a = List("red","blue","green","black")
val b = a.tail :+ a.head
or to make it safer:
//val a = Nil
val a = List("red","blue","green","black")
//val a = List("red")
val b = a match {
case Nil => Nil
case h :: t => t :+ h
}
println(b)

Alejandro Alcalde
- 5,990
- 6
- 39
- 79
-
1How is the second one "safer"? It crashes for `Nil` in exactly the same way as the first one, because `Nil.tail` throws an exception: `java.lang.UnsupportedOperationException: tail of empty list`. It doesn't even compile properly, because it produces a `List[Any]`... – Andrey Tyukin Jan 29 '19 at 16:34
-
Oh!, didn't thought of the tail case. Let me update it. Thanks for pointing it out. – Alejandro Alcalde Jan 29 '19 at 16:39
-
-
1While you are at it, you could at least do `case h :: t => t :+ h` to avoid an extra call to `tail` and `head`. – Andrey Tyukin Jan 29 '19 at 16:43
-
But, in that case statement, isn't the `unapply` method calling internally `head` and `tail`? – Alejandro Alcalde Jan 29 '19 at 16:46
-
1Yes, it [does again call `.head` and `.tail`](https://github.com/scala/scala/blob/2.13.x/src/library/scala/collection/package.scala#L70). That's why I wrote [`::`](https://github.com/scala/scala/blob/2.13.x/src/library/scala/collection/immutable/List.scala#L576) and not `+:`. I am for some reason pretty certain that pattern matching on case-classes should be a little bit more efficient than calling an extractor method on some unrelated object. – Andrey Tyukin Jan 29 '19 at 16:49