【发布时间】:2020-02-26 08:22:15
【问题描述】:
我正在阅读 Scala 中的函数式编程,但无法理解一段代码。我已经检查了这本书的勘误表,并且有问题的段落没有印刷错误。 (其实确实有错印,但错印不影响我有疑问的代码。)
有问题的代码计算一个小于某个上限的伪随机非负整数。执行此操作的函数称为nonNegativeLessThan。
trait RNG {
def nextInt: (Int, RNG) // Should generate a random `Int`.
}
case class Simple(seed: Long) extends RNG {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL // `&` is bitwise AND. We use the current seed to generate a new seed.
val nextRNG = Simple(newSeed) // The next state, which is an `RNG` instance created from the new seed.
val n = (newSeed >>> 16).toInt // `>>>` is right binary shift with zero fill. The value `n` is our new pseudo-random integer.
(n, nextRNG) // The return value is a tuple containing both a pseudo-random integer and the next `RNG` state.
}
}
type Rand[+A] = RNG => (A, RNG)
def nonNegativeInt(rng: RNG): (Int, RNG) = {
val (i, r) = rng.nextInt
(if (i < 0) -(i + 1) else i, r)
}
def nonNegativeLessThan(n: Int): Rand[Int] = { rng =>
val (i, rng2) = nonNegativeInt(rng)
val mod = i % n
if (i + (n-1) - mod >= 0) (mod, rng2)
else nonNegativeLessThan(n)(rng2)
}
我无法理解nonNegativeLessThan 中如下所示的代码:if (i + (n-1) - mod >= 0) (mod, rng2) 等
这本书解释说,整个 if-else 表达式是必要的,因为简单地采用 nonNegativeInt 的结果的 mod 的简单实现会稍微偏向较低的值,因为 Int.MaxValue 不能保证是n.因此,此代码旨在检查生成的nonNegativeInt 的输出是否大于适合 32 位值的 n 的最大倍数。如果生成的数字大于适合 32 位值的 n 的最大倍数,则函数重新计算伪随机数。
详细来说,简单的实现如下所示:
def naiveNonNegativeLessThan(n: Int): Rand[Int] = map(nonNegativeInt){_ % n}
其中map定义如下
def map[A,B](s: Rand[A])(f: A => B): Rand[B] = {
rng =>
val (a, rng2) = s(rng)
(f(a), rng2)
}
重复一遍,这种幼稚的实现是不可取的,因为当 Int.MaxValue 不是 n 的完美倍数时会略微偏向较低的值。
所以,重申一下这个问题:下面的代码做了什么,它如何帮助我们确定一个数字是否小于适合 32 位整数的 n 的最大倍数?我说的是nonNegativeLessThan里面的这段代码:
if (i + (n-1) - mod >= 0) (mod, rng2)
else nonNegativeLessThan(n)(rng2)
【问题讨论】:
-
据我所知,它没有做任何事情,因为条件永远不会 false。由于
i保证为非负数,而n假定 为正数,这将mod置于零到n-1的范围内,包括0 到n-1。所以(n-1) - mod也是非负数。因此if条件始终为true。
标签: scala random functional-programming mod