简体   繁体   English

递归遍历 Scala 列表

[英]Recursively iterate through a Scala list

I'm trying to recursively iterate through a list in Scala using pattern matching.我正在尝试使用模式匹配递归遍历 Scala 中的列表。 I cannot use any list functions, or while/for loops.我不能使用任何列表函数或 while/for 循环。 What I need to do is iterate through the list, and remove an element if it matches to be '4'.我需要做的是遍历列表,如果匹配为“4”,则删除一个元素。 I'm new to Scala and I cannot find the answer in the textbook I have nor on google.我是 Scala 的新手,在我拥有的教科书和谷歌上都找不到答案。 Everyone else uses the filter method, or some other list method.其他人都使用过滤器方法或其他一些列表方法。

Here's what I tried to do (which is wrong)这是我试图做的(这是错误的)

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
}

See if this works for you.看看这是否适合你。

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

Usage:用法:

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

Using an inner function and pattern matching to de-structure the list.使用内部函数和模式匹配来解构列表。 If the head in the list is 4 , then do not add it to the accumulator.如果列表中的头是4 ,则不要将其添加到累加器中。 If it is, append it to the accumulator.如果是,则将其附加到累加器。

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

The preferred way to do this is with guards in the pattern match but the if else statement may look more familiar if you're just getting started with scala.执行此操作的首选方法是在模式匹配中使用守卫,但如果您刚刚开始使用 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())
}

I am not sure about the execution time.我不确定执行时间。 I am also new to scala but I am taking bollean approach to filter any list.我也是 scala 的新手,但我正在采用布尔方法来过滤任何列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM