【问题标题】:Recursively iterate through a Scala list递归遍历 Scala 列表
【发布时间】:2016-04-30 08:42:06
【问题描述】:

我正在尝试使用模式匹配递归遍历 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
}

【问题讨论】:

    标签: scala recursion functional-programming pattern-matching


    【解决方案1】:

    使用内部函数和模式匹配来解构列表。如果列表中的头是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())
    }
    

    【讨论】:

    • @tailrec 注释添加到loop 函数以确保它不吃堆栈。在这种情况下不会,但它始终是一个好习惯。
    【解决方案2】:

    看看这是否适合你。

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 2014-03-01
      • 2021-10-05
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2021-10-11
      • 2012-03-27
      相关资源
      最近更新 更多