为什么大多数 Scala 库都使用可变的 RNG

Why do most Scala libraries use mutable RNG

在 Cats 文档中,在描述 State monad 的使用时给出了 pure functional PRNG 的一个吸引人的实现。但是,我见过的库(Breeze、Spire)使用了可变生成器。为什么?另外,是否有任何库使用 Cats 方法?

Jörg W Mittag 在评论中写道:

If I had to make a guess, though, I would have one idea: yes, dealing with mutable state is hard. But, writing a good PRNG, especially a CSPRNG is also hard. Maybe, the authors just thought that dealing with the mutable state of an already existing, vetted, battle-tested PRNG would be easier than creating their own? Note that especially for a CSPRNG, not only the cryptographic properties are important but also the performance. Otherwise, your super-safe super-pure CSPRNG just becomes an attack vector for a DoS attack. Also, beware of timing attacks and other side channels.

In particular, the RNG you linked to has some well-known disadvantages, and is not recommended for cryptographic usage.

实际上接受的答案没有抓住要点。由于 RNG 本身的质量,Breeze & Spire 不使用可变 RNG。他们这样做是为了 编程方便

功能性 RNG 需要以 state-monad 形式编写程序(如 Cats 文档中所示),通常在 for-expressions 中使用 RNG 的所有用法。如果存在 OptionFuture 等其他单子效应,则需要通过 monad-transformers.

等方式组合它们