【发布时间】:2014-08-20 10:32:27
【问题描述】:
我在 99 个 scala 问题 (http://aperiodic.net/phil/scala/s-99/p03.scala) 中遇到了一个问题,我试图弄清楚它是如何工作的。我对 Scala 还很陌生。我能够通过使用模式匹配和递归的类似解决方案完成这一挑战,但是我没有考虑匹配中的列表。我的代码如下:
def nth[A](k: Int, l: List[A]): A = k match {
case 0 => l.head
case _ => nth(k-1, l.drop(1))
}
这似乎完成了这项工作。但是,如果列表为 Nil,则不会检查错误。 99个scala问题提供的解决方案是:
def nthRecursive[A](n: Int, ls: List[A]): A = (n, ls) match {
case (0, h :: _ ) => h
case (n, _ :: tail) => nthRecursive(n - 1, tail)
case (_, Nil ) => throw new NoSuchElementException
}
我不明白的是
case(0, h:: _ )
和
case(n, _ :: tail)
作者在这里做什么?我了解 :: 将左侧的内容附加到右侧内容的开头,但我不确定到底发生了什么。谁能赐教?
谢谢!
【问题讨论】:
标签: list scala recursion pattern-matching