【问题标题】:Scala for loop yieldScala for 循环产量
【发布时间】:2023-04-02 18:15:01
【问题描述】:

我是 Scala 的新手,所以我试图弄乱 Scala 编程中的一个示例:全面的分步指南,第 2 版

  // Returns a row as a sequence
  def makeRowSeq(row: Int) =
    for (col <- 1 to 10) yield {
      val prod = (row * col).toString
      val padding = " " * (4 - prod.length)
      padding + prod
  }
  // Returns a row as a string
  def makeRow(row: Int) = makeRowSeq(row).mkString
  // Returns table as a string with one row per line
  def multiTable() = {
    val tableSeq = // a sequence of row strings
      for (row <- 1 to 10)
      yield makeRow(row)
    tableSeq.mkString("\n")
  }

调用multiTable()时上面的代码输出:

  1   2   3   4   5   6   7   8   9  10
  2   4   6   8  10  12  14  16  18  20
  3   6   9  12  15  18  21  24  27  30
  4   8  12  16  20  24  28  32  36  40
  5  10  15  20  25  30  35  40  45  50
  6  12  18  24  30  36  42  48  54  60
  7  14  21  28  35  42  49  56  63  70
  8  16  24  32  40  48  56  64  72  80
  9  18  27  36  45  54  63  72  81  90
  10  20  30  40  50  60  70  80  90 100

这是有道理的,但如果我尝试将 multiTable() 中的代码更改为:

  def multiTable() = {
    val tableSeq = // a sequence of row strings
      for (row <- 1 to 10)
      yield makeRow(row) {
        2
      }
    tableSeq.mkString("\n")
  }

正在返回 2 并更改输出。我不确定它在哪里被用来操纵输出,并且似乎无法在此处或 Google 中找到类似的示例。任何输入将不胜感激!

【问题讨论】:

  • 你正在有效地这样做:yield (makeRow(row)(2))
  • 这是否意味着 makeRow(row) * 2?
  • 即“取字符串的第2个字符(从零开始)”
  • 现在说得通了。再次感谢您的帮助

标签: scala


【解决方案1】:
makeRow(row) {2}

makeRow(row)(2)

makeRow(row).apply(2)

都是等价的。

makeRow(row) 是 List[String] 类型,每个String 代表一行。如此有效,您从每一行中选择索引 2 处的字符。这就是为什么您会在输出中看到 9 个空格和一个 1。

  def multiTable() = {
    val tableSeq = // a sequence of row strings
      for (row <- 1 to 10)
        yield makeRow(row) {2}
    tableSeq.mkString("\n")
  }

相当于在每一行上应用一个映射

  def multiTable() = {
    val tableSeq = // a sequence of row strings
      for (row <- 1 to 10)
        yield makeRow(row)
    tableSeq.map(_(2)).mkString("\n")
  }

【讨论】:

  • 太棒了,这完全有道理。谢谢!
猜你喜欢
  • 2017-02-07
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多