从 for-comprehension 转换为 map 的问题

Problem in converting from for-comprehension to map

我正在尝试将 Scala for comprehension 转换为使用 map,但我 运行 遇到了问题。

为了说明,请考虑以下按预期工作的转换。

scala> for (i <- 0 to 10) yield i * 2
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

scala> 0 to 10 map { _ * 2 }
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

但是,以下方法不起作用。我犯了什么错误?

scala> import util.Random
import util.Random

scala> for (i <- 0 to 10) yield Random.nextInt(10)
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 0, 7, 5, 9, 4, 6, 6, 6, 3, 0)

scala> 0 to 10 map { Random.nextInt(10) }
<console>:13: error: type mismatch;
 found   : Int
 required: Int => ?
       0 to 10 map { Random.nextInt(10) }
                                   ^

根本原因可能是我无法正确解读错误消息或修复原因。当我查看 Random.nextInt 的签名时,它似乎返回了一个 Int

scala> Random.nextInt
   def nextInt(n: Int): Int   def nextInt(): Int

错误消息说我需要提供一个接受 Int 和 returns "something" 的函数(不确定 ? 代表什么)。

required: Int => ?

所以我可以看出不匹配。但是我如何将我想要发生的事情——对 Random.nextInt(10) 的调用——转换为函数并将其传递给 map?

如能帮助理解以下错误消息,我们将不胜感激。

scala> 0 to 10 map { Random.nextInt(10) }
<console>:13: error: type mismatch;
 found   : Int
 required: Int => ?
       0 to 10 map { Random.nextInt(10) }
                                   ^

(编辑)

执行以下操作会有所帮助。

scala> def foo(x: Int): Int = Random.nextInt(10)
foo: (x: Int)Int

scala> 0 to 10 map { foo }
res10: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 1, 7, 6, 5, 1, 6, 0, 7, 4)

但是对此的评论或推荐的 Scala 方式的建议将不胜感激。

错误消息中的 Int => ? 意味着编译器希望看到从 Int 到其他类型 (?) 的函数。但是 Random.nextInt(10) 不是一个函数,它只是一个 Int。你必须带一个整数参数:

0 to 10 map { i => Random.nextInt(10) }

您也可以明确忽略参数:

0 to 10 map { _ => Random.nextInt(10) }

或者,更好的是,只需使用 fill:

Vector.fill(10){ Random.nextInt(10) }