交换列表中 x 元素的正确方法
我开始学习Scala语言,我有一个问题。您认为以函数式风格交换 List 中第一个和最后一个 x 元素是否是正确的方法?
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
}
如果 x 超过列表长度的一半,发生什么并不重要。我有兴趣了解算法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这段代码是正确的并且具有合理的功能风格。它不是最有效的,因为它必须遍历列表四次才能创建
l1
到l3
片段。另外,您可能想保留列表包含的类型,因此略有改进是: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
throughl3
. Also, you probably want to preserve the type that the list contains, so a slight improvement is:我尝试了一下,效果很好:
你自己提供的代码有什么问题吗?
I tried it and it worked fine:
Is there anything wrong with the code you provided yourself?