Scala:具有内部递归函数的函数

Scala:具有内部递归函数的函数,scala,recursion,Scala,Recursion,我正在编写一个函数,该函数从列表中删除第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

我正在编写一个函数,该函数从列表中删除第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一直在抱怨
案例(any,h::tl)
不可访问


但是如果我调用
removea4(3,List('a,'b,'c,'d,'e,'f))
不应该
case(startPos,h::tl)
被有效地翻译成
case(3,h::tl)

在你的第二个例子中
case(startPos,h::tl)
不会做你认为它做的事情。它定义了一个元组,其中新变量startPos绑定到元组的第一个元素。本质上,它与您的最后一个case
case(any,h::tl)
相同,因此最后一个case是不可访问的

顺便说一句,我有一个你可以适应的答案:

def removeAt(startPos:Int, inputList:List[Symbol]) = {
    list.zipWithIndex.collect {
        case (x,i) if i != startPos == 0 => x
    }
}