如何在函数式编程风格中创建Scala中的列表列表

时间:2016-05-29 16:09:22

标签: scala functional-programming purely-functional

我想在Scala中创建一个函数,给定List[Int]返回List[List[Int]]。例如,getCombs(List(1,2))应返回List(List(1), List(2), List(1,2))

我正在学习函数式编程,所以我想用这个范例来完成我的任务。

我已经创建了以下功能并且它可以工作,但我认为在函数式编程风格中有更好的方法来完成这项工作。

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
}

2 个答案:

答案 0 :(得分:2)

我首先创建一系列我想要制作的所有组合长度,然后使用flatMap创建所有组合并从中创建一个列表:

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

答案 1 :(得分:1)

(1 to coins.length).flatMap { 
  coins.combinations(_)  
}.toList