【发布时间】:2025-12-22 22:25:16
【问题描述】:
我正在编写一个从列表中删除第 k 个元素的函数(这来自 scala 99 问题)并且对特定行为感到困惑 这个递归函数很好用
def removeAt3(startPos:Int, inputList :List[Symbol]) = {
// will use inner recursive function
def removeAtRecursive(position:Int, lst:List[Symbol]):List[Symbol] = (position, lst) match {
case (_, Nil) => println("end of list");List[Symbol]()
case (any, h::tl) => if (any == startPos) removeAtRecursive(any + 1, tl) else h::removeAtRecursive(any+1, tl)
}
removeAtRecursive(0, inputList)
}
但是这个版本没有。
def removeAt4(startPos:Int, inputList :List[Symbol]) = {
// will use inner recursive function
def removeAtRecursive(position:Int, lst:List[Symbol]):List[Symbol] = (position, lst) match {
case (_, Nil) => println("end of list");List[Symbol]()
case (startPos, h::tl) => removeAtRecursive(position + 1, tl)
case (any, h::tl) => h::removeAtRecursive(any+1, tl)
}
removeAtRecursive(0, inputList)
}
removeAt4(3, List('a, 'b, 'c, 'd, 'e, 'f))
事实上 Eclipse 一直在抱怨 case(any, h::tl) 无法访问。
但是如果我打电话给removeAt4(3, List('a, 'b, 'c, 'd, 'e, 'f)),case(startPos, h::tl) 不应该被有效地翻译成case(3, h::tl)吗?
【问题讨论】: