我只想要一个函数,如果 true
的所有元素相互跟随,即返回 List[Integer]
noGaps(List(3,4,5)) // true
noGaps(List(4,3,5)) // false
noGaps(List(3,4,6)) // false
我有一些有用的东西,但有点冗长 - 最优雅的解决方案是什么?
最佳答案
这个怎么样?
def noGaps(xs: Seq[Int]) =
xs.size < 2 || xs.sliding(2).forall { case Seq(x, y) => y == x + 1 }
关于list - 检查列表是否没有间隙的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6926746/