Scala 嵌套循环产量

标签 scala loops for-loop

我想知道在 scala 中是否有一种简单的方法可以做这样的事情:

case class Pot(width: Int, height: Int, flowers: Seq[FlowerInPot])
case class FlowerInPot(x: Int, y: Int, flower: String)

val flowers = Seq("tulip", "rose")
val height = 3
val width = 3

val res =
  for (flower <- flowers;
       h <- 0 to height;
       w <- 0 to width) yield {
       // ??
  }

在输出中,我想要一个 Seq of Pots,其中放置了所有可能的花组合。所以在下面的例子中,输出应该是:

Seq(
  Pot(3, 3, Seq(FlowerInPot(0, 0, "tulip"), FlowerInPot(0, 1, "rose"))),
  Pot(3, 3, Seq(FlowerInPot(0, 0, "tulip"), FlowerInPot(0, 2, "rose"))),
  Pot(3, 3, Seq(FlowerInPot(0, 0, "tulip"), FlowerInPot(1, 0, "rose"))),
  Pot(3, 3, Seq(FlowerInPot(0, 0, "tulip"), FlowerInPot(1, 1, "rose"))),
  ...
  Pot(3, 3, Seq(FlowerInPot(2, 2, "tulip"), FlowerInPot(2, 1, "rose")))
)

有什么想法吗?

最佳答案

这是你想要的吗?

case class FlowerInPot(x: Int, y: Int, flower: String)
case class Pot(width: Int, height: Int, flowers: Seq[FlowerInPot])

val x, y = 0
val flowers = Seq("tulip", "rose")
val height = 3
val width = 3

val res = for {
  h <- 0 to height
  w <- 0 to width
} yield Pot(height, width, flowers.map(flower => FlowerInPot(w, h, flower)))

关于Scala 嵌套循环产量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23617576/

相关文章:

loops - 如何比较 lisp 中长度或结构不完全相同的两个列表?

java - 在循环中使用 Map.put(String, Integer)

c - 在 for 循环中打印二维数组会使程序崩溃

python - C 中的 For 循环没有明显原因提前中断 - 可能与函数指针(回调)有关

java - 字符数组无法正确读取输入

scala - Scala 中可以制作作用域计时器吗?

scala - 什么时候应该用现在分词与过去分词调用方法,即排序与排序或反向与反向?

java - 使用 Java 中的用户输入创建 X 模式?

scala - 如何使用 Scala 使用 Hadoop 客户端在 HDFS 中 append 文本文件?

scala - 如何使用特征处理数据?