如何以函数式编程风格在 Scala 中创建列表列表
How to create a List of Lists in Scala in functional programming style
我想在 Scala 中创建一个给定 List[Int]
returns 和 List[List[Int]]
的函数。例如 getCombs(List(1,2))
应该 returns 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
}
(1 to coins.length).flatMap {
coins.combinations(_)
}.toList
我首先创建了一个范围内的所有长度的组合,然后我使用 flatMap
来创建所有组合并列出它们:
def allCombinations(list: List[Int]): List[List[Int]] = {
(1 to list.length).flatMap(list.combinations(_)).toList
}
我想在 Scala 中创建一个给定 List[Int]
returns 和 List[List[Int]]
的函数。例如 getCombs(List(1,2))
应该 returns 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
}
(1 to coins.length).flatMap {
coins.combinations(_)
}.toList
我首先创建了一个范围内的所有长度的组合,然后我使用 flatMap
来创建所有组合并列出它们:
def allCombinations(list: List[Int]): List[List[Int]] = {
(1 to list.length).flatMap(list.combinations(_)).toList
}