Problem 03
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
package ninetyNineScalaProblems
|
||||
|
||||
import scala.annotation.tailrec
|
||||
|
||||
object Problem03:
|
||||
def nthElement(list: List[Any], n: Int): Option[Any] =
|
||||
@tailrec
|
||||
def loop(cursor: List[Any], acc: Int): Option[Any] =
|
||||
cursor match
|
||||
case e :: tail if acc == n =>
|
||||
Some(e)
|
||||
case e :: tail =>
|
||||
loop(tail, acc + 1)
|
||||
case Nil =>
|
||||
None
|
||||
|
||||
loop(list, 0)
|
||||
|
||||
object Problem03Stdlib:
|
||||
def nthElement(list: List[Any], n: Int): Option[Any] =
|
||||
list.drop(n).headOption
|
||||
Reference in New Issue
Block a user