Search code examples
randomelm

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


Is initialSeed supposed to provide a different seed each time it is called? The following code always provides the same value:

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

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

If this code is behaving correctly, would you kindly give a pointer on the usage of random numbers and Random.generate.


Solution

  • initialSeed is a function which given an Int produces a Seed which can then be used in the generate function. Because Elm is purely function, giving generate the same Generator and Seed will always produce the same value. However, generate also returns the next Seed to be used in your next call to generate. This in allows you to reproduce the same sequence of randomly generated values.

    Example usage:

    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]
    

    on share-elm.com: http://share-elm.com/sprout/55c766b4e4b06aacf0e8be1b

    Hope this helps!