use*_*745 4 functional-programming scala
我想过滤收集,因此相邻元素之间的距离至少为5.
所以List(1, 2, 3, 4, 5, 6, 7, 11, 20)
会成为List(1, 6, 11, 20)
.
是否可以使用过滤器一次完成?什么是scala-way?
这个单行怎么样:
scala> l.foldLeft(Vector(l.head)) { (acc, item) => if (item - acc.last >= 5) acc :+ item else acc }
res7: scala.collection.immutable.Vector[Int] = Vector(1, 6, 11, 20)
Run Code Online (Sandbox Code Playgroud)
试试foldLeft()
:
val input = List(1, 2, 3, 4, 5, 6, 7, 11, 20)
input.tail.foldLeft(List(input.head))((out, cur) =>
if(cur - out.head >= 5) cur :: out else out
).reverse
Run Code Online (Sandbox Code Playgroud)
如果不明显:
算法从output
集合中的第一个元素开始(可能需要处理一些边缘情况)
它遍历所有剩余的元素input
.如果此element(cur
)与第一个元素之间的差异input
大于或等于5
,则前置为input
.否则跳过并继续
input
通过前置和检查head
来建立以获得更好的性能..reverse
最终需要
这基本上是以命令式方式实现它的方式,但语法更简洁.