林Scala的模式匹配打,试图让FindNext中发现的功能列表中的下一个元素:使用模式匹配
findNext(1,List(1,2,3)) == 2
findNext(2,List(1,2,3)) == 3
findNext(3,List(1,2,3)) == 1
def findNext(needle : Int, haystack : List[Int]): Int = {
haystack match {
case Nil => /* handle it */
case needle::Nil => needle
case front::needle::back => back.head
case needle::back::Nil => back.head
}
}
我可以使它只工作在平凡的情况。
可以这样使用模式匹配来完成?我知道我可以使用列表中的方法使其工作,但这只是一个玩具程序。
+1表示@tailrec,因为这是处理“下一个”的更直接简单的方法。 – wheaties 2013-03-28 03:52:24