How to map list items with their tail [Scala]

Viewed 294

How does one map each item in a list iteratively with it's remaining tail? Pseudo code example:

val list = List(1,2,3,4) 
list.foreach((head, tail) => println(s"head= $head, tail= $tail")) 
// head= 1, tail = List(2, 3, 4) 
// head= 2, tail = List(3, 4) 
// head= 3, tail = List(4) 
// head= 4, tail = List()
3 Answers

The easiest way seems to be the good old for-loop, which has the advantage that it inserts a filtering step for you, so you don't crash on the Nil case while iterating over the tails:

for (h :: t <- (1 to 4).toList.tails) println(s"head: $h tail: $t")

gives:

head: 1 tail: List(2, 3, 4)
head: 2 tail: List(3, 4)
head: 3 tail: List(4)
head: 4 tail: List()

If you don't actually need the println-side effect, a for-yield would give you just the values.

def rec(l: List[Int]) : Unit = {
    l match {
        case head::tail => println(s"head= $head, tail= $tail")
            rec(tail)
        case _ =>
    }
}

scala> rec(l)
    head= 1, tail= List(2, 3, 4)
    head= 2, tail= List(3, 4)
    head= 3, tail= List(4)
    head= 4, tail= List()

A (to me) more straightforward answer. As @LuisMiguelMejíaSuárez says, tails is your friend

(xs zip xs.tails.toList) map {case (h, t) => println("Head: " + h + " Tail: " + t)}

The .toList is a pity, though


Related