Example:
scala> nth(2, List(1, 1, 2, 3, 5, 8)) res0: Int = 2
--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
This is all pretty cool, I would just remove some fluff:def nth[T](n: Int, list: List[T]): Option[T] = {list match {case Nil => Nonecase head :: tail => if (n < 0) None else if (n== 0) head else nth(n - 1, tail)}}
scala> def nth[T](n: Int, list: List[T]): Option[T] = {
| list match {
| case Nil => None
| case head :: tail => if (n < 0) None else if (n== 0) Some(head) else nth(n - 1, tail)
| }
| }
nth: [T](n: Int, list: List[T])Option[T]
scala> nth(42, Nil)
res1: Option[Nothing] = None
scala> nth(0, List(1, 2))
res2: Option[Int] = Some(1)
scala> nth(1, List(1, 2))
res3: Option[Int] = Some(2)
scala> nth(2, List(1, 2))
res4: Option[Int] = None
def nth[T](n: Int, list: List[T]): Option[T] = list.lift(n)
--
def nth[T](n: Int, xs: List[T]) = xs.drop(n-1).headOption
I’ve worked through some of the S99 problems myself (and problems in other texts). What I don’t understand is what functions are you “allowed” to use when solving the problem. It seems that non-[tail]recursive answers are avoiding use of the “index operator” () in exchange for other seemingly more advanced methods methods like drop, take.
def nth[A](n: Int, l: List[A]): Option[A] = if(n < 0 || n >= l.length) None else Some(l(n))
I understand that using () defeats the purpose of the exercise, but it seems like drop, take etc., do the same thing? What do you guys think? (At the same time, if you never use other List methods, almost every exercise would be some kind of tail recursion)
Some of the (easy) problems can be trivially solved using built-in functions. However, in these cases, you learn more if you try to find your own solution.