递归遍历Scala列表

Col*_*lby 1 recursion functional-programming scala pattern-matching

我正在尝试使用模式匹配递归迭代Scala中的列表.我不能使用任何列表函数,或while/for循环.我需要做的是遍历列表,如果匹配为'4',则删除一个元素.我是Scala的新手,我在教科书中找不到答案,也没有在谷歌上找到答案.其他人都使用过滤方法或其他一些列表方法.

这是我试图做的(这是错的)

def removeFours(lst: List[Int]): List[Int] = {
val newLst = lst
lst match {
  case Nil => Nil
  case a if a == 4 => newLst -= 0
  case n => removeFours(newLst)
}
newLst
}
Run Code Online (Sandbox Code Playgroud)

jwv*_*wvh 7

看看这是否适合你.

def removeFours(lst: List[Int], acc: List[Int] = List.empty): List[Int] = {
  lst match {
     case Nil    => acc.reverse
     case 4 :: t => removeFours( t, acc )
     case h :: t => removeFours( t, h :: acc )
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

scala> removeFours( List(3,7,4,9,2,4,1) )
res84: List[Int] = List(3, 7, 9, 2, 1)
Run Code Online (Sandbox Code Playgroud)