用于Scala中的理解

时间:2013-05-10 20:31:27

标签: scala for-comprehension

def combinations(occurrences: List[(Char,Int)]): List[List[(Char,Int)]] = occurrences match {
  case Nil => Nil
  case x :: xs => for(z <- combinations(xs); y <- occ(x)) yield (y :: z)
}

def occ(e: (Char, Int)): List[(Char, Int)] = (for(i <- 0 to e._2) yield (e._1, i)).toList

您好,

我在上面的代码片段中找不到任何缺陷,但它仍然为我提供任何输入的List()。

3 个答案:

答案 0 :(得分:10)

嗯,我认为你非常接近答案。最重要的是考虑Nil的正确回报值。

  def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match {
    case Nil => List(List())
    case x :: xs => 
      for {
        z <- combinations(xs)
        n <- 0 to x._2
      } yield (if (n == 0) z else (x._1, n) :: z)
  }

答案 1 :(得分:2)

您首先理解,在递归结束时总会产生Nil,这会强制您的其余递归为Nil。这是一个略有修改的版本,虽然它提供List[(Char, Int)]而不是List[List[(Char, Int)]]

def combinations(occurrences: List[(Char,Int)]): List[(Char,Int)] = occurrences match {
  case Nil => Nil
  case x :: xs => (for { z <- combinations(xs) } yield z) ::: occ(x)
}

如果您的理解的第一部分返回Nil,那么它将不会评估其余部分,只会返回Nil。我已经改变了一些东西,所以现在即使评估为Nil,它也会与occ的结果相结合。

答案 2 :(得分:1)

def combinations(occurrences: List[(Char,Int)]): List[List[(Char,Int)]] = occurrences match {
  case Nil => List(List())
  case x :: xs => for(z <- combinations(xs); y <- occ(x)) yield (y :: z)
}

def occ(e: (Char, Int)): List[(Char, Int)] = (for(i <- 0 to e._2) yield (e._1, i)).toList

这解决了我的问题!!!

相关问题