user1224087
user1224087

Reputation: 3

List in scala -getting element from the right side

I have started learning scala and I wonder is there a way I could get elements in the List from the right side

For example

val myList = List(1, 2, 3, 4, 5)

if I writemyList(-1) I would get 5.

Is there any simple way to get it done or I'll have to write my own function?

Upvotes: 0

Views: 971

Answers (4)

wingedsubmariner
wingedsubmariner

Reputation: 13667

To do something like:

myList(-n)

You can define an implicit conversion that lets you do:

myList.getFromRight(n)

Here is the code for the implicit conversion. It will create a new getFromRight method on all Seqs, so it will work on Lists, Vectors, etc.

implicit def getFromRightImpl[A](s: Seq[A]) = new {
  def getFromRight(n: Int) = s(s.length - n)
}

And here are some examples:

scala> val v = Vector(1, 2, 3, 4)
v: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4)

scala> val l = List(1, 2, 3, 4)
l: List[Int] = List(1, 2, 3, 4)

scala> v.getFromRight(1)
res4: Int = 4

scala> l.getFromRight(3)
res5: Int = 2

Implicit conversions are a rather advanced Scala feature, but this is one of the perfect use cases for them: when an object is lacking methods you think it should have, but modifying it with inheritance is not an option, you can define an implicit conversion to another object with the methods you want.

Upvotes: 0

missingfaktor
missingfaktor

Reputation: 92116

Scala's List is a singly linked list, and therefore indexed lookup on it would be a linear time operation. Since you are interested in backward indices, you'll also have to call .length method, which is a linear time operation as well.

If you need to perform indexed access, List is probably not the right data structure to use. You should instead use Vector which is a sequence type with efficient indexed access (takes constant time effectively).

Refer this link for an overview of performance characteristics of various Scala collections.

scala> val v = Vector(3, 4, 5, 2)
v: scala.collection.immutable.Vector[Int] = Vector(3, 4, 5, 2)

scala> v(v.length - 1)
res21: Int = 2

Upvotes: 1

Dave Griffith
Dave Griffith

Reputation: 20515

myList(myList.length-1-index)

Note then myList.length has O(n) complexity, and querying for specific index has O(index).

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 341003

myList.last

? Remember that this operation has O(n) complexity for List. Also you can simply reverse the list and use normal indices:

myList.reverse(0)

Upvotes: 4

Related Questions