Search code examples
scalafor-comprehension

Scala: for comprehension on each list of a nested list


Here is a simple for comprehension to get all combinations of letters between two Lists

val two = List('a', 'b', 'c')
val three = List('d', 'e', 'f')
val res = for {
  i <- two
  j <- three
} yield s"$i$j"
println(res.mkString("[", ",", "]"))

// [ad, ae, af, bd, be, bf, cd, ce, cf]

Now, lets say we have a list of such lists

val list = List(two, three)

How do I write for comprehensions to get same result as first case? This list could be larger list like List(two, three, seven, nine) etc?


Solution

  • As @MateuszKubuszok suggested.

    object LetterCombinationsScala extends App {
    
      def combinations(digits: String): List[String] = {
        val map = Map(2 -> "abc", 3 -> "def", 4 -> "ghi", 5-> "jkl",6 -> "mno", 7 -> "pqrs", 8 -> "tuv", 9 -> "wxyz")
        digits
          .toCharArray
          .map(_.toInt - '0'.toInt)
          .map(map)
          .map(_.toCharArray)
          .foldLeft(List(""))((is, js) => {
            for {
              i <- is
              j <- js
            } yield s"$i$j"
        })
      }
    
        val res = combinations("293")
        println(res.mkString("[", ",", "]"))
    }
    // [awd,awe,awf,axd,axe,axf,ayd,aye,ayf,azd,aze,azf,bwd,bwe,bwf,bxd,bxe,bxf,byd,bye,byf,bzd,bze,bzf,cwd,cwe,cwf,cxd,cxe,cxf,cyd,cye,cyf,czd,cze,czf]