arpanchaudhury
arpanchaudhury

Reputation: 237

Using for comprehension in Scala

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.

Upvotes: 2

Views: 2067

Answers (3)

deltamaster
deltamaster

Reputation: 111

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)
  }

Upvotes: 10

arpanchaudhury
arpanchaudhury

Reputation: 237

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!!!

Upvotes: 1

Noah
Noah

Reputation: 13959

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.

Upvotes: 2

Related Questions