My Avatar

Shilong ZHAO

[s 99] p03 kth element of list

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

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

Find the Kth element of a list.

By convention, the first element in the list is element 0. Example:

scala> nth(2, List(1, 1, 2, 3, 5, 8))
res0: Int = 2
def nth[T](n: Int, list: List[T]): Option[T] = 
    if (n < list.size) Some(list(n)) else None

val l = List(1,2,3)
nth(0, l)
nth(3, l)

//l(3)
def nthRecursive[T](n: Int, list: List[T]): Option[T] = 
    if (n == 0) list.headOption
    else if (list.isEmpty) None
    else nthRecursive(n - 1, list.tail)

def nthWithMatch[T](n: Int, list: List[T]): Option[T] = list match {
    case Nil => None
    case x::xs if (n == 0) => Some(x)
    case _::xs => nthWithMatch(n - 1, list.tail)
}

val p = List("a", "b", "c")
nthRecursive(2, p)
nthRecursive(3, p)

nthWithMatch(2, p)
nthWithMatch(3, p)