Scala for loop yield

时间:2016-05-22 23:15:48

标签: scala

我是Scala的新手,所以我试图在Scala编程中使用一个示例:一个全面的循序渐进指南,第二版

  // 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并更改输出。我不知道它在哪里用于操纵输出,似乎找不到类似的例子在这里搜索或谷歌。任何输入将不胜感激!

1 个答案:

答案 0 :(得分: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")
  }