递归遍历Scala列表

时间:2016-01-23 21:09:06

标签: scala recursion functional-programming 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
}

2 个答案:

答案 0 :(得分: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 )
  }
}

用法:

scala> removeFours( List(3,7,4,9,2,4,1) )
res84: List[Int] = List(3, 7, 9, 2, 1)

答案 1 :(得分:2)

使用内部函数和模式匹配来解构列表。如果列表中的头部为4,则不要将其添加到累加器中。如果是,请将其附加到累加器。

def removeFours(lst: List[Int]): List[Int] = {
  def loop(lst: List[Int], acc: List[Int]): List[Int] = lst match {
    case Nil => acc
    case h :: t =>
      if (h == 4) {
        loop(t, acc)
      }else{
        loop(t, acc :+ h)
      }
  }
  loop(lst, List())
}

执行此操作的首选方法是在模式匹配中使用防护,但如果您刚开始使用scala,则if else语句可能看起来更为熟悉。

def removeFours(lst: List[Int]): List[Int] = {
  def loop(lst: List[Int], acc: List[Int]): List[Int] = lst match {
    case Nil => acc
    case h :: t if (h == 4) => loop(t, acc)
    case h :: t  => loop(t, acc :+ h)
  }
  loop(lst, List())
}