Random Numbers in Elm

Our program will demonstrate how to generate random numbers in Elm. Here’s the full source code:

module Main exposing (main)

import Random
import Html exposing (Html, div, text)
import Task


main : Program () Model Msg
main =
    Html.program
        { init = init
        , view = view
        , update = update
        , subscriptions = always Sub.none
        }


type alias Model =
    { randomInt : Int
    , randomFloat : Float
    , randomRange : Float
    }


type Msg
    = NewRandomInt Int
    | NewRandomFloat Float
    | NewRandomRange Float


init : ( Model, Cmd Msg )
init =
    ( Model 0 0 0
    , Cmd.batch
        [ Random.generate NewRandomInt (Random.int 0 99)
        , Random.generate NewRandomFloat Random.float
        , Random.generate NewRandomRange (Random.float 5 10)
        ]
    )


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NewRandomInt n ->
            ( { model | randomInt = n }, Cmd.none )

        NewRandomFloat n ->
            ( { model | randomFloat = n }, Cmd.none )

        NewRandomRange n ->
            ( { model | randomRange = n }, Cmd.none )


view : Model -> Html Msg
view model =
    div []
        [ text <| "Random Int (0-99): " ++ String.fromInt model.randomInt
        , Html.br [] []
        , text <| "Random Float (0-1): " ++ String.fromFloat model.randomFloat
        , Html.br [] []
        , text <| "Random Float (5-10): " ++ String.fromFloat model.randomRange
        ]

In this Elm program, we’re using the Random module to generate random numbers.

The Random.int 0 99 generates a random integer between 0 and 99 (inclusive).

Random.float generates a random float between 0 and 1.

We can generate random floats in other ranges, for example between 5 and 10, using Random.float 5 10.

To run this program, you would typically compile it to JavaScript and run it in a browser. The output would look something like this:

Random Int (0-99): 42
Random Float (0-1): 0.7231742859293372
Random Float (5-10): 7.914528302913614

Note that the actual numbers will be different each time you run the program.

In Elm, we don’t have the concept of a seeded random number generator that we can create and reuse. Instead, random number generation is handled through commands and the Elm runtime, ensuring that the state of the random number generator is managed properly in a functional setting.

For more information on random number generation in Elm, you can refer to the Random module documentation.