开发者

Right way to swap x elements in List

开发者 https://www.devze.com 2023-01-13 16:41 出处:网络
I started to learn Scala langu开发者_如何学运维age 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?

I started to learn Scala langu开发者_如何学运维age 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.


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
}


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消