递归遍历Scala列表

3
我尝试使用模式匹配在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
}
3个回答

8

请看看这是否对您有用。

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)

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())
}

loop函数中添加@tailrec注解,以确保它不会消耗堆栈。在这种情况下,它不会,但这总是一个好习惯。 - Alexey Raga

0

我对执行时间不太确定。我也是新手,但我正在采用布尔方法来过滤任何列表。

object Main extends App {
//fun that will remove 4
  def rm_4(lst: List[Int]) : List[Int] = {
    val a = lst.filter(kill_4)
    a
  }
// boolean fun for conditions
  def kill_4(n: Int) : Boolean = {
    if (n ==4) false
    else true
  }
println(rm_4(List(1,2,4,5,4))) // outpur List(1,2,5)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接