查找列表的子列表的递归调用返回空

时间:2014-06-12 20:08:31

标签: list scala recursion

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

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

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

1 个答案:

答案 0 :(得分: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)
    }
  }