功能总是返回Nil

时间:2016-01-27 09:55:13

标签: list scala dictionary recursion for-comprehension

我正在尝试解决一些字谜任务。我无法弄清楚在运行sentenceAnagrams函数时总是得到List()的问题。任何帮助!

type Word = String
type Sentence = List[Word]
type Occurrences = List[(Char, Int)]


  def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match {
  case Nil => List(Nil)
  case x :: xs => (for {z <- combinations(xs); i <- 1 to x._2} yield (x._1, i) :: z).union(combinations(xs))
}



def subtract(x: Occurrences, y: Occurrences): Occurrences = {
if (y.isEmpty) x
else {
  val yMap = y.toMap withDefaultValue 0
  x.foldLeft(x) { (z, i) => if (combinations(x).contains(y)) {
    val diff = i._2 - yMap.apply(i._1)
    if (diff > 0) z.toMap.updated(i._1, diff).toList else z.toMap.-(i._1).toList
  } else z
  }
}}

-

 def sentenceAnagrams(sentence: Sentence): List[Sentence] = {

    def sentenceAnag(occ: Occurrences): List[Sentence] =

      if (occ.isEmpty) List(List())
      else (for {
        comb <- combinations(occ)
        word <- (dictionaryByOccurrences withDefaultValue List()).apply(comb)
        otherSentence <- sentenceAnag(subtract(occ, comb))
      } yield word :: otherSentence).toList

    sentenceAnag(sentenceOccurrences(sentence))
  }

0 个答案:

没有答案