And*_*day 3 functional-programming scala
我想在功能样式中重构这段Scala代码:
var k = -1
for (i <- 0 until array.length)
if ((i < array.length - 1) && array(i) < array(i + 1))
k = i
Run Code Online (Sandbox Code Playgroud)
Scala中的数组indexWhere,可以用于类似的东西val index = array.indexWhere(c => c == 'a').我正在寻找类似的东西,它将考虑数组的两个连续元素.
Tra*_*own 16
当你需要查看集合中的相邻元素时,通常的功能方法是用它的尾部"压缩"集合.请考虑以下简化示例:
scala> val xs = List(5, 4, 2, 3, 1)
xs: List[Int] = List(5, 4, 2, 3, 1)
scala> val tail = xs.tail
tail: List[Int] = List(4, 2, 3, 1)
scala> xs.zip(tail)
res0: List[(Int, Int)] = List((5,4), (4,2), (2,3), (3,1)
Run Code Online (Sandbox Code Playgroud)
现在我们可以使用indexWhere:
scala> res0.indexWhere { case (x, y) => x < y }
res1: Int = 2
Run Code Online (Sandbox Code Playgroud)
在您的情况下,以下内容基本上等同于您的代码:
val k = (array zip array.tail) lastIndexWhere { case (x, y) => x < y }
Run Code Online (Sandbox Code Playgroud)
我正在使用lastIndexWhere而不是indexWhere,因为在你的代码中,当你遇到一个谓词所在的对时,你不会停止循环.
Ada*_*ung 11
sliding 给你滑动窗口进入集合,即
scala> Array(1,2,2,4,5,6, 6).sliding(2).toList
res12: List[Array[Int]] = List(Array(1, 2), Array(2, 2), Array(2, 4), Array(4, 5), Array(5, 6), Array(6, 6))
Run Code Online (Sandbox Code Playgroud)
这样就可以轻松找到第一个匹配对的索引:
Array(1,2,2,4,5,6, 6).sliding(2).indexWhere { case Array(x1, x2) => x1 == x2 }
Run Code Online (Sandbox Code Playgroud)
这只会给你第一个索引,collect用来捕捉所有人!
Array(1,2,2,4,5,6, 6)
.sliding(2) //splits each in to pairs
.zipWithIndex //attaches the current index to each pair
.collect { case (Array(x1, x2), index) if (x1 == x2) => index } //collect filters out non-matching pairs AND transforms them to just the inde
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10675 次 |
| 最近记录: |