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

时间:2016-05-30 09:38:13

标签: 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 ]
            ]

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

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

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

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

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

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

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

init =
    ( Model 0, (Random.generate NewFace (Random.int 10 70)) )

    NewFace newFace ->
        ( Model (newFace // 10), Cmd.none )

1 个答案:

答案 0 :(得分:3)

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

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

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