My Avatar

Shilong ZHAO

[s 99] p01 last element in list

2020-06-22 00:00:00 +0200

In case you have any questions or suggestions, you can leave comments HERE . Thanks!

P01 Find the last element of a list.

Example:

scala> last(List(1, 1, 2, 3, 5, 8))
res0: Int = 8
@scala.annotation.tailrec
def last[T](list: List[T]): T = list match {
    case Nil => throw new NoSuchElementException
    case e::Nil => e
    case _::t => last(t)
}

last(List(1,2,3,4,5))
last(Nil)

def lastByReverse[T](list: List[T]): T = list.reverse.head

lastByReverse(List(1,2,3,4,5))
lastByReverse(Nil)
def lastByIndex[T](list: List[T]): T = list(list.size - 1)
lastByIndex(List(1,2,3,4,5))
lastByIndex(Nil)

Find last element in list returning Option

def lastOp[T](list: List[T]): Option[T] = list match {
    case Nil => None
    case e::Nil => Some(e)
    case _::t => lastOp(t)
}

lastOp(Nil)
lastOp(List("a","b","c"))
def lastByReverseOp[T](list: List[T]): Option[T] = if (list.isEmpty) None else Some(list.reverse.head)
lastByReverseOp(List())
lastByReverseOp(Nil)
lastByReverseOp(List(1,2,3,4))
def lastByIndexOp[T](list: List[T]): Option[T] = if (list.isEmpty) None else Some(list(list.size - 1))
lastByIndexOp(List(1,2,3,4,5))
lastByIndexOp(Nil)