Search code examples
scalafunctional-programmingpurely-functional

How to create a List of Lists in Scala in functional programming style


I want to create a function in Scala that given a List[Int] returns a List[List[Int]]. For example getCombs(List(1,2)) should returns List(List(1), List(2), List(1,2)).

I'm studying functional programming so I would like to accomplish my task using that paradigm.

I've created the following function and it works, but I think that there exist a better way to do the job in a functional programming style.

def getCombs(coins: List[Int]): List[List[Int]] = {

  var l = List(coins)
  var i = 0
  for (i <- 1 to coins.length - 1) {
    var it = coins.combinations(i)
    while (it.hasNext) {
      val el = it.next
      val newL = el :: l
      l = newL

    }

  }
  return l
}

Solution

  • I first create a range of all the lengths of combinations that I want to make, then I use flatMap to create all the combinations and make a list out of them:

    def allCombinations(list: List[Int]): List[List[Int]] = {
        (1 to list.length).flatMap(list.combinations(_)).toList
    }