Skip to content

Runtime error on certain recursive random-number generators #1529

@alex-lew

Description

@alex-lew

This issue can be replicated in Chrome and Safari on Mac OS X in elm-lang.org/try.

import Html exposing (Html, div, text, button)
import Html.Events exposing (onClick)
import Random


-- PROBLEM

rollIf : Bool -> Random.Generator Int
rollIf b =
  if b then
    Random.int 1 6
  else
    tryAgain

rollAgain : Random.Generator Int
rollAgain =
  roll

roll : Random.Generator Int
roll =
  Random.bool
    |> Random.andThen rollIf


-- SUPPORT CODE

main =
  Html.program
    { init = (0, Cmd.none)
    , update = update
    , view = view
    , subscriptions = always Sub.none
    }

view model =
  div []
    [ text (toString model)
    , button [onClick Generate] [text "Generate!"]
    ]

type Msg = Generate | NewValue Int

update msg model =
  case msg of
    Generate ->
      (model, Random.generate NewValue roll)

    NewValue v ->
      (v, Cmd.none)

Clicking "Generate" a few times will cause the following runtime error:

TypeError: undefined is not an object (evaluating '_p59._0')

If the definition of rollAgain is removed in favor of using roll directly, the runtime error disappears and the code works as expected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions