Problem 03

This commit is contained in:
2026-03-19 15:39:09 +01:00
parent 9001e72a27
commit 6504948100
2 changed files with 34 additions and 0 deletions
@@ -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
@@ -0,0 +1,13 @@
package ninetyNineScalaProblems
class Problem03Suite extends munit.FunSuite:
List(
((List(1, 2, 3, 4, 5), 0), Some(1)),
((List(1, 2, 3, 4, 5), 2), Some(3)),
((List(1), 1), None),
((List(), 0), None)
).foreach:
case ((list, n), expected) =>
test(s"nthElement returns [$expected]"):
assertEquals(Problem03.nthElement(list, n), expected)
assertEquals(Problem03Stdlib.nthElement(list, n), expected)