In [1]:
val list1 = List(1, 1, 2, 3, 5, 8)
In [4]:
def lastBuildin[A](ls: List[A]): A = ls.last
In [5]:
def lastRecursive[A](ls: List[A]): A = ls match {
case h :: Nil => h
case _ :: tail => lastRecursive(tail)
case _ => throw new NoSuchElementException
}
In [6]:
lastBuildin(list1)
In [7]:
lastRecursive(list1)
In [8]:
def penultimateBuildin[A](ls: List[A]): A =
if(ls.isEmpty) throw new NoSuchElementException
else ls.init.last
In [9]:
def penultimateRecursive[A](ls: List[A]): A = ls match {
case h :: _ :: Nil => h
case _ :: tail => penultimateRecursive(tail)
case _ => throw new NoSuchElementException
}
In [10]:
penultimateBuildin(list1)
In [12]:
penultimateRecursive(list1)
In [ ]: