Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive List concatenation

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.

like image 867
André Rüdiger Avatar asked Jun 24 '26 13:06

André Rüdiger


1 Answers

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)
like image 183
pagoda_5b Avatar answered Jul 01 '26 14:07

pagoda_5b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!