【问题标题】:Scala: function with inner recursive functionScala:具有内部递归函数的函数
【发布时间】: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)吗?

【问题讨论】:

    标签: scala recursion


    【解决方案1】:

    在你的第二个例子中,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
        }
    }
    

    【讨论】: