每次调用initialSeed是否应该提供不同的种子?以下代码始终提供相同的值:
ArrayList
如果此代码表现正常,您是否可以指出随机数和Random.generate的使用情况。
答案 0 :(得分:3)
initialSeed
是一个函数,它给Int
生成Seed
,然后可以在generate
函数中使用generate
。因为Elm是纯函数,所以Generator
Seed
和generate
相同,总是会产生相同的值。但是,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]
时使用。这允许您重现相同的随机生成值序列。
使用示例:
{{1}}
在share-elm.com上:http://share-elm.com/sprout/55c766b4e4b06aacf0e8be1b
希望这有帮助!
答案 1 :(得分:1)
在Elm 0.15中使用Random
非常容易。 (我假设您了解Elm如何自然地将数据和代码分离为模型,更新和视图。如果您对Elm架构的理解不稳定,请阅读The Elm Architecture教程和simple explanation of model-view-update pattern)。
最重要的功能是generate
,它返回一对:随机值和新种子。这个新种子你可以再次传递给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