2013-05-14 165 views
2

我寫了轉換時間戳列表間間隔轉換時間戳間間隔

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()) 
    } 

,無尾調用

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) 
     } 
    } 

Scala的功能,但我有一種感覺,有一個一/二襯裏它例如map2。有什麼建議?

回答

6
(timestamps.tail, timestamps).zipped.map(_.toLong - _.toLong) 

是你的單線;儘管(這會使它成爲雙線),但它只會更有效率地運行val times = timestamps.map(_.toLong)一次。

1

接受的答案是偉大的,只是想提供一種替代方案:

timetamps.sliding(2).map { case Seq(a,b) => b - a }