Random.initialSeed 在 elm (v0.15) 中的预期行为是什么

What is the expected behaviour of Random.initialSeed in elm (v0.15)

initialSeed 是否应该在每次调用时提供不同的种子?以下代码始终提供相同的值:

import Graphics.Element exposing (show)
import Random exposing(float, generate, initialSeed)

main = 
    show (generate (float 0 1 ) (initialSeed 31415))

如果此代码运行正确,请指点一下随机数的用法和 Random.generate。

initialSeed 是一个函数,给定一个 Int 生成一个 Seed,然后可以在 generate 函数中使用。因为 Elm 是纯函数,给 generate 相同的 GeneratorSeed 将始终产生相同的值。但是,generate 还 returns 下一个 Seed 将在您下次调用 generate 时使用。这允许您重现相同序列的随机生成值。

用法示例:

import Random
import Graphics.Element as Element

-- Int Generator that computes random numbers in the range [0, 10]
intGenerator = Random.int 0 10

-- Change this to get different sequences.
seed = Random.initialSeed 42
--seed = Random.initialSeed 1234
--seed = Random.initialSeed 0

-- Generates a random x and returns the next seed to be used. Note:
-- This will always return the same x because it uses the same seed
-- this is a result of Elm being purely functional. However,
-- because this returns a new seed, you can use that to get the next
-- random value in the sequence
(x, seed') = (Random.generate intGenerator seed)

-- Generate the next element in the sequence
(y, seed'') = (Random.generate intGenerator seed')
(z, seed''') = (Random.generate intGenerator seed'')

main = Element.show [x, y, z]

分享-elm.com:http://share-elm.com/sprout/55c766b4e4b06aacf0e8be1b

希望对您有所帮助!

使用 Random is super-easy in Elm 0.15. (I assume you understand how Elm naturally separates data and code into model, update, and view. If your understanding of Elm architecture is shaky, read The Elm Architecture tutorial and simple explanation of model-view-update pattern).

最重要的函数是generate,它returns一对:随机值和新种子。您可以再次将这个新种子传递给 generate,以产生一个新的随机值和另一个种子。然而,传递相同的种子会产生相同的“随机”值。下面的代码呈现 59:

import Graphics.Element exposing (show)
import Random exposing (generate, int, initialSeed)

main =
  let (number, seed) = generate (int 0 99) (initialSeed 1234)
  in show number

您需要以某种方式在任意 2 个随机值生成之间保存这个新种子。并且每次使用 generate 时,传递新种子而不是旧种子。你是怎么做到的?

您将种子存储在模型中并确保在更新阶段用新种子覆盖旧种子:

import Graphics.Element exposing (Element, show)
import Mouse exposing (clicks)
import Random exposing (Seed, initialSeed, generate, int)
import Signal exposing (Signal, foldp)

seed0 = initialSeed 1234

type alias Model = { num : Int, seed : Seed }

defaultModel : Model
defaultModel = { num = 0, seed = seed0 } -- initial seed in the model

update : () -> Model -> Model
update _ model =
  let (newNum, newSeed) = generate (int 0 99) model.seed -- new value and new seed
  in { model | num <- newNum, seed <- newSeed } -- update model with new seed

view : Model -> Element
view model = show model.num

-- new random value each time mouse clicked
main = Signal.map view <| foldp update defaultModel clicks