用于Scala中的理解

arp*_*ury 2 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
Run Code Online (Sandbox Code Playgroud)

嗨,

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

小智 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)
  }
Run Code Online (Sandbox Code Playgroud)