【发布时间】:2011-09-26 06:40:14
【问题描述】:
// But pattern matching also makes it easy.
def penultimateRecursive[A](ls: List[A]): A = ls match {
case h :: _ :: Nil => h
case _ :: tail => penultimateRecursive(tail)
case _ => throw new NoSuchElementException
}
有人可以逐行评论这是在做什么吗?
[A] 是否像 c# 中的泛型,我们会这样做吗?
h 好像没有定义?
我认为算法的主要部分是递归调用:
case _ :: tail => penultimateRecursive(tail)
似乎没有'检查列表中的2项,然后取第1项获得最后2项,困惑!
【问题讨论】:
标签: list scala recursion functional-programming pattern-matching