Lukasz Madon
Lukasz Madon

Reputation: 15004

convert timestamps to intervals

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

Answers (2)

Ryan LeCompte
Ryan LeCompte

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

Rex Kerr
Rex Kerr

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

Related Questions