2
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

Hi,

I can't find any flaw in the above snippet but it still giving me List() for any input.

3 Answers 3

10

Well, I think you are pretty close to the answer. The most important thing is to consider what is the right return value in case of 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)
  }
Sign up to request clarification or add additional context in comments.

1 Comment

You could also decompose x to improve readability. Just replace case x :: xs => for case (char, times) :: xs =>
2

You're first for comprehension will always yield a Nil at the end of your recursion which will force the rest of your recursion to be Nil. Here's a slightly modified version that works, though it gives a List[(Char, Int)] instead of a 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)
}

If the first part of your for comprehension returns Nil, then it won't evaluate the rest of it and will just return Nil. I've changed things around a bit, so now even if it does evaluate to Nil, it will be combined with the results of occ.

Comments

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

This has solved my problem!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.