Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing the last element of a list

Tags:

list

scala

scala> last(List(1, 1, 2, 3, 5, 8)) res0: Int = 8 

for having a result above, I wrote this code:

val yum = args(0).toInt val thrill:   def last(a: List[Int]): List[Int] = {      println(last(List(args(0).toInt).last)      } 

What is the problem with this code?

like image 736
dondog Avatar asked Feb 24 '11 11:02

dondog


People also ask

How do I get the last element in a list?

Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want last element in list, use -1 as index.

How do you slice the last 5 elements of a list in Python?

Method #2 : Using islice() + reversed() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.


2 Answers

You can use last, which returns the last element or throws a NoSuchElementException, if the list is empty.

scala> List(1, 2, 3).last res0: Int = 3 

If you do not know if the list is empty or not, you may consider using lastOption, which returns an Option.

scala> List().lastOption res1: Option[Nothing] = None  scala> List(1, 2, 3).lastOption res2: Option[Int] = Some(3) 

Your question is about List, but using last on a infinite collection (e.g. Stream.from(0)) can be dangerous and may result in an infinite loop.

like image 138
michael.kebe Avatar answered Sep 30 '22 08:09

michael.kebe


Another version without using last (for whatever reason you might need it).

def last(L:List[Int]) = L(L.size-1) 
like image 40
Jus12 Avatar answered Sep 30 '22 07:09

Jus12