Reputation: 15004
I wrote a scala function that converts list of timestamps to intervals
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())
}
and without tailcall
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)
}
}
but I have a feeling that there is a one/two liner for it e.g map2 . Any advice?
Upvotes: 2
Views: 173
Reputation: 4321
The accepted answer is great, just wanted to offer an alternative:
timetamps.sliding(2).map { case Seq(a,b) => b - a }
Upvotes: 1
Reputation: 167901
(timestamps.tail, timestamps).zipped.map(_.toLong - _.toLong)
is your one-liner; it's more efficient to val times = timestamps.map(_.toLong)
only once, though (which would make it a two-liner).
Upvotes: 6