Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how to get a slice of a list from nth element to the end of the list without knowing the length?

Tags:

scala

I'm looking for an elegant way to get a slice of a list from element n onwards without having to specify the length of the list. Lets say we have a multiline string which I split into lines and then want to get a list of all lines from line 3 onwards:

string.split("\n").slice(3,X)       // But I don't know what X is... 

What I'm really interested in here is whether there's a way to get hold of a reference of the list returned by the split call so that its length can be substituted into X at the time of the slice call, kind of like a fancy _ (in which case it would read as slice(3,_.length)) ? In python one doesn't need to specify the last element of the slice.

Of course I could solve this by using a temp variable after the split, or creating a helper function with a nice syntax, but I'm just curious.

like image 341
Mark Silberbauer Avatar asked Mar 06 '13 22:03

Mark Silberbauer


People also ask

How to use slice in Scala?

In Scala API, 'slice' function is used to select an interval of elements. It takes two parameters of “Int” type and returns subset or whole or none element(s) of original Collection (or String or Array). Real-world slice scenario:- We can use this slice function in our regular real-world life too as shown below.

How do I append to a list in Scala?

This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.


2 Answers

Just drop first n elements you don't need:

List(1,2,3,4).drop(2) res0: List[Int] = List(3, 4) 

or in your case:

string.split("\n").drop(2) 

There is also paired method .take(n) that do the opposite thing, you can think of it as .slice(0,n).

In case you need both parts, use .splitAt:

val (left, right) = List(1,2,3,4).splitAt(2) left: List[Int] = List(1, 2) right: List[Int] = List(3, 4) 
like image 118
om-nom-nom Avatar answered Sep 23 '22 19:09

om-nom-nom


The right answer is takeRight(n):

"communism is sharing => resource saver".takeRight(3)                                               //> res0: String = ver 
like image 42
Val Avatar answered Sep 21 '22 19:09

Val