Luk*_*don 2 functional-programming scala
我写了一个scala函数,将时间戳列表转换为间隔
def toIntervals(timestamps: List[String]) = {
def helper(timestamps: List[String], accu: List[Long]): List[Long] = {
if (timestamps.tail.isEmpty) accu.reverse
else {
val first = timestamps.head.toLong
val second = timestamps.tail.head.toLong
val newHead = second - first
helper(timestamps.tail, newHead :: accu)
}
}
helper(timestamps, List())
}
Run Code Online (Sandbox Code Playgroud)
没有尾巴
def toIntervals(timestamps: List[String]) : List[Long] = {
if (timestamps.tail.isEmpty) List()
else {
val first = timestamps.head.toLong
val second = timestamps.tail.head.toLong
val newHead = second - first
newHead :: toIntervals(timestamps.tail)
}
}
Run Code Online (Sandbox Code Playgroud)
但我觉得它有一个/两个衬垫,例如map2.有什么建议?
(timestamps.tail, timestamps).zipped.map(_.toLong - _.toLong)
Run Code Online (Sandbox Code Playgroud)
是你的一线; 虽然它val times = timestamps.map(_.toLong)只有一次效率更高(这会使它成为一个双线).
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |