Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala iterate through list except last element

Tags:

for-loop

scala

Using a for loop, how can I iterate through a list, with the ability to not iterate over the very last element in the list.

In my case, I would like to not iterate over the first element, and need to iterate through backwards, here is what I have:

        for( thing <- things.reverse) {
          //do some computation iterating over every element; 
          //break out of loop when first element is reached
        }
like image 387
user1553248 Avatar asked Dec 08 '22 09:12

user1553248


2 Answers

You can drop the first item before you reverse it:

for(thing <- things.drop(1).reverse) {
}

For lists, drop(1) is the same as tail if the list is non-empty:

for(thing <- things.tail.reverse) {
}

or you could do the reverse first and use dropRight:

for(thing <- things.reverse.dropRight(1)) {
}

You can also use init if the list is non-empty:

for(thing <- things.reverse.init) {
}
like image 178
Lee Avatar answered Dec 18 '22 09:12

Lee


As mentioned by Régis, for(thing <- things.tail.reverse) {}

like image 28
Yann Moisan Avatar answered Dec 18 '22 09:12

Yann Moisan