tags:

views:

121

answers:

2

I started to learn Scala language and I have a question. How do you think, is it a right way to swap first and last x elements in List in a functional style?

def swap(l: List[Any], x: Int) = {
  val l1 = l.take(x)
  val l2 = l.slice(x, l.length - x)
  val l3 = l.takeRight(x)
  l3 ::: l2 ::: l1
}

It doesn't matter what happened if x would be more than half list length. I'm interested to find out algorithm.

+2  A: 

I tried it and it worked fine:

scala> swap(List(1, 2, 3, 4, 5),2)
res0: List[Any] = List(4, 5, 3, 1, 2)

Is there anything wrong with the code you provided yourself?

olle kullberg
+5  A: 

This code is correct and is in a reasonable functional style. It's not the most efficient since it has to traverse the list four times to create the pieces l1 through l3. Also, you probably want to preserve the type that the list contains, so a slight improvement is:

def swap[A](l: List[A], x: Int) = {
  val (l1,rest) = l.splitAt(x)
  val (l2,l3) = rest.splitAt(rest.length-x)
  l3 ::: l2 ::: l1
}
Rex Kerr