【问题标题】:Scala recursion function that removes number from list needs work从列表中删除数字的Scala递归函数需要工作
【发布时间】:2016-05-04 07:13:44
【问题描述】:

我有一个递归方法,它应该从给定列表中删除所有零。

def removeZ(list:List[Int], n:Int):List[Int] = list match {
  case Nil => Nil
  case h::t=>
    if (h == n)
      t
    else 
      h :: removeZ(t,n)
}

这会从列表中删除一个零,但如果列表中有多个零,则不会。我尝试添加另一个不起作用的 if else 语句,例如:

if else(t==n)
   removeZ(t,n)

如何删除所有零?

【问题讨论】:

    标签: scala function recursion


    【解决方案1】:

    那是因为在返回尾部的第一个 0 之后,你必须不断迭代:

    scala> def removeZ(list: List[Int], n: Int): List[Int] = list match {
       |     case Nil => Nil
       |     case h :: t =>
       |       if (h == n)
       |         removeZ(t, n) // 0 found, skip it and iterate the tail
       |       else
       |         h :: removeZ(t, n)
       |   }
    removeZ: (list: List[Int], n: Int)List[Int]
    
    scala> removeZ(List(1,0,2,0,3), 0)
    res0: List[Int] = List(1, 2, 3)
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2016-01-08
      • 2020-09-08
      • 1970-01-01
      • 2016-10-09
      相关资源
      最近更新 更多