榆树 - 初始奇怪行为的随机数

Joh*_*rin 6 random elm

只需处理样本,就可以创建2个随机骰子并用按钮滚动它们.

http://guide.elm-lang.org/architecture/effects/random.html

所以我想我会将骰子创建为模块,删除滚动动作,然后让它在init上创建D6值.

所以我的代码现在如下(应该直接在elm-reactor中打开)

module Components.DiceRoller exposing (Model, Msg, init, update, view)

import Html exposing (..)
import Html.App as Html
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Random
import String exposing (..)

main =
    Html.program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }



-- MODEL


type alias Model =
    { dieFace : Int
    }


init : ( Model, Cmd Msg )
init =
    ( Model 0, (Random.generate NewFace (Random.int 1 6)) )



-- UPDATE


type Msg
    = NewFace Int


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NewFace newFace ->
            ( Model newFace, Cmd.none )



-- SUBSCRIPTIONS


subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none



-- VIEW


dieFaceImage : Int -> String
dieFaceImage dieFace =
    concat [ "/src/img/40px-Dice-", (toString dieFace), ".svg.png" ]


view : Model -> Html Msg
view model =
    let
        imagePath =
            dieFaceImage model.dieFace
    in
        div []
            [ img [ src imagePath ] []
            , span [] [ text imagePath ]
            ]
Run Code Online (Sandbox Code Playgroud)

这个问题是它总是产生相同的值.我以为我的种子开始有问题,但如果你改变了

init =
    ( Model 0, (Random.generate NewFace (Random.int 1 6)) )

init =
    ( Model 0, (Random.generate NewFace (Random.int 1 100)) )
Run Code Online (Sandbox Code Playgroud)

它完全按照预期工作.所以看起来默认生成器不能处理小值,似乎工作低至10.

奇怪的是,在这个例子中(我开始使用)http://guide.elm-lang.org/architecture/effects/random.html,当它不在init时,它适用于1-6.

所以我的问题是,我做错了什么,或者这只是榆树的皱纹?我在init中使用该命令是否正常?

最后,我把它放进去以获得理想的效果,感觉很不稳定.

init =
    ( Model 0, (Random.generate NewFace (Random.int 10 70)) )
Run Code Online (Sandbox Code Playgroud)

    NewFace newFace ->
        ( Model (newFace // 10), Cmd.none )
Run Code Online (Sandbox Code Playgroud)

mar*_*gio 6

这一定和播种有关系。您没有为种子指定任何值,因此生成器默认使用当前时间。

我认为您尝试在几秒钟内刷新页面几次,但没有看到值发生变化。如果您等待更长的时间(大约一分钟),您会看到您的值发生变化。

我查看了Random的源代码,我怀疑对于足够接近的种子值,在 [1,6] 范围内生成的第一个值不会改变。我不确定这是否符合预期,也许值得在 GitHub 上提出问题