I have the following function that returns a list of distances between the elements of a list of integers:
def dists(l: List[Int]) = {
//@annotation.tailrec
def recurse(from: Int, rest: List[Int]): List[Int] = rest match {
case Nil => Nil
case to :: tail => to - from :: recurse(to, tail)
}
l match {
case first :: second :: _ => recurse(first, l.tail)
case _ => Nil
}
}
The :: prevents me from using the @tailrecannotation although it seems that the call to recurse is in tail position.
Is there a @tailrec compatible way to do the concatenation?
I could use an accumulator but then I would have to inverse the input or the output, right?
Edit: I am especially interested in the recursive approach. My concrete use case is a bit more complicated in that one call to recurse could add several items to the result list:
=> item1 :: item2:: recurse(...)
The distance function is just an example to demonstrate the problem.
This is not a reply to the exact original request, it's an alternative solution to the problem.
You can simply zip the list with the same list "shifted" by one position and then map the resulting zipped list to the difference of the tupled elements.
In code
def dist(l: List[Int]) = l.zip(l drop 1) map { case (a,b) => b - a}
If you have trouble understanding what' s going on I suggest splitting the operation and explore on the REPL
scala> val l = List(1,5,8,14,19,21)
l: List[Int] = List(1, 5, 8, 14, 19, 21)
scala> l zip (l drop 1)
res1: List[(Int, Int)] = List((1,5), (5,8), (8,14), (14,19), (19,21))
scala> res1 map { case (a, b) => b - a }
res2: List[Int] = List(4, 3, 6, 5, 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With