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

时间:2015-03-05 16:57:42

标签: 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) 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)是否应该被有效翻译?

1 个答案:

答案 0 :(得分:0)

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

顺便说一下,this question有一个你可以适应的答案:

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