Search code examples
randomelm

How can I compare random number in elm


I use float : Signal a -> Signal Float to generate random number.

I want to compare this generated number with a Float, how can I do that?

main = lift asText ((Random.float (fps 24)) < 0.3)

This is wrong, error message:

    (Random.float (fps 24)) < 0.3

    Expected Type: Bool
    Actual Type: Signal.Signal a

Solution

  • The best way to debug this type of thing is to follow the types. Break every part into a separate piece, examine the types and resolve the type error.

    We have a few things here:

    lift : (a -> b) -> Signal a -> Signal b
    asText : a -> Element
    Random.float : Signal a -> Signal Float
    fps : number -> Signal Time
    (<) : number -> number -> Bool
    

    Okay, so let's start plugigng in values and resolving the types:

    fps 24 : Signal Time
    Random.float (fps 24) : Signal Float
    (Random.float (fps 24)) < 0.3 : ???
    

    This is where our type error is coming from. We are trying to pass in a Signal but the (<) operator only accepts number. So, what we actually want is a function that compares the value in our Signal to see if it is < 0.3.

    foo : Float -> Bool
    foo n = n < 0.3
    

    Now, we can lift foo and pass the signal into it:

    lift foo (Random.float (fps 24))
    

    And then plug it back into our original expression:

    main = list asText (lift foo (Random.float (fps 24)))
    

    Now, all of the types resolve.

    Hope this helps!