How to get a random value in the range defined by the signal?

First code:

import Random
import Window

writeRandom x = lift asText (Random.range 0 x <| every second)

upperLimit = 300
-- upperLimit = Window.width -- How can i use this instead?

main = writeRandom upperLimit

      

Ultimately, I'm trying to get random points on the screen, but I can't figure out how to pass Window.height and Window.width to Random.range. I don't think I can "raise" Random.range as it already returns a signal. If I try to get an error like:

Type Error: 'main' must have type Element or (Signal Element).
Instead 'main' has type:

   Signal (Signal Element)

      

And I'm not sure if the opposite of an elevator (below?) Exists or even makes sense.

thank

+2


source to share


1 answer


You are correct in thinking that the opposite of the lower is meaningless.
In this particular case, the built-in Random library is built due to the fact that it wraps a native JavaScript call. This is the reason for the return type Signal

to keep the code clean. And even then, not very well behaved .

To get the random range you want, you'll need a different random number generator. There is a community library that was published just a few days ago, which will probably answer your needs. You can check it yourself from GitHub, or use elm-get

.

Your code will become something like (untested!):



import Window
import Generator
import Generator.Standard as GStd

randomSeed = 12346789

writeRandom : Signal Int -> Signal Element
writeRandom x = 
  let update high (_, gen) = Generator.int32Range (0,high) gen
      start = (0, GStd.generator randomSeed)
      input = sampleOn (every second) x
      result = fst <~ foldp update start input
  in  lift asText result

upperLimit = Window.width

main = writeRandom upperLimit

      

In writeRandom

you are using foldp

to store the last random number generator. As update

you use it to get a new random number generator and the new next time. The input is x

updated every second with sampleOn (every second)

. The part fst <~

is for removing the random number generator since you only need the random number.

+3


source







All Articles