package problems
import scala.annotation.tailrec
/**
* Created by t.papillon on 22/12/2016.
*/
object Solutions {
@tailrec
def last[A](l: List[A]): Option[A] = l match {
case List() => None
case List(x) => Some(x)
case _ :: xs => last(xs)
}
@tailrec
def penultimate[A](l: List[A]): Option[A] = l match {
case List() | List(_) => None
case List(x, _) => Some(x)
case _ :: xs => penultimate(xs)
}
@tailrec
def nth[A](n: Int, l: List[A]): Option[A] = l match {
case _ if n < 0 => None
case List() if n >= 0 => None
case x :: xs if n == 0 => Some(x)
case _ :: xs => nth(n - 1, xs)
}
def length[A](l: List[A]): Int = {
@tailrec
def aux(acc: Int, l: List[A]): Int = l match {
case List() => acc
case _ :: xs => aux(acc + 1, xs)
}
aux(0, l)
}
def reverse[A](l: List[A]): List[A] = {
@tailrec
def aux(acc: List[A], l: List[A]): List[A] = l match {
case List() => acc
case x :: xs => aux(x :: acc, xs)
}
aux(List(), l)
}
}