【问题标题】:Recursive call to find the sub lists of a list returns empty递归调用查找列表的子列表返回空
【发布时间】:2014-08-03 07:01:45
【问题描述】:
def find(list: List[(Char,Int)]):  List[(Char,Int)] = {
  list match {
    case List() => List()
    case (z,y):: xs => ((for(i <- 1 to y) yield (z,i)).toList ::: find(xs).toList)
  }  

find(List(('a',5),('b',3))) // will return nothing at all

我简直无法理解为什么这样的函数会为给定的参数返回空值。它没有空的参数,所以这里可能是什么问题?

这可能是一个非常简单的问题,但我真的需要一双新的眼睛来帮助我调试这个问题,因为我根本无法发现我犯的愚蠢错误

【问题讨论】:

    标签: list scala recursion


    【解决方案1】:

    您的函数似乎对我正常工作,因为它返回以下内容:

    List((a,1), (a,2), (a,3), (a,4), (a,5), (b,1), (b,2), (b,3))
    

    我确实注意到您提供的代码中您的 find 函数缺少右括号,它应该如下所示:

      def find(list: List[(Char, Int)]): List[(Char, Int)] = {
        list match {
          case List() => List()
          case (z, y) :: xs => (for (i <- 1 to y) yield (z, i)).toList ::: find(xs)
        }
      }
    

    【讨论】:

    • 似乎不需要在find(xs) 上调用toList,因为find 已经返回List
    • @Noah 看起来我在工作表中定义了它并忘记实际调用它。我看到的返回是函数的返回。如果我使用工作表,这就是我得到的。不,你不能笑
    猜你喜欢
    • 2014-01-18
    • 2020-01-22
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多