简单这样做的方法是什么?
Random.initialSeed的文档说:
"A good way to get an unexpected seed is to use the current time."
http://package.elm-lang.org/packages/elm-lang/core/2.1.0/Random#initialSeed
经过大量阅读,我只能找到"解决方案"这远远超出了我对榆树和功能编程的理解。它们似乎也不是解决这个问题的方法。
我目前正在硬编码:
Random.initialSeed 314
如果您使用库,请包含用于从elm包获取它的名称。我已经看到了一个使用Native.now
的解决方案,但我无法弄清楚如何获得该解决方案。
stackoverflow建议这个,但我无法理解如何将它应用到我的用例Elm Current Date
答案 0 :(得分:1)
你可以从https://msdn.microsoft.com/library/dd383458%28v=vs.100%29.aspx
尝试案例纳尔逊的回答来自elm repl:
> import Now
> import Random
> Now.loadTime |> round -- get current time in Int
1455406828183 : Int
> Now.loadTime |> round |> Random.initialSeed -- get the Seed
Seed { state = State 1560073230 678, next = <function>, split = <function>, range = <function> }
: Random.Seed
我的代码How do I get the current time in Elm?上也有代码。
注意:请勿忘记"native-modules": true
中的elm-package.json
。
编辑:
尝试代码,
"native-modules": true
elm-package.json
答案 1 :(得分:0)
我能想到的最简单的方法是使用Elm Architecture和Effects.tick
机制用时间值初始化种子。
这是一个如何工作的例子:
import Html exposing (..)
import Html.Events exposing (onClick)
import Random exposing (Seed, generate, int, initialSeed)
import Time exposing (Time)
import Effects exposing (Effects, Never)
import Task exposing (Task)
import StartApp
type alias Model = { seed : Seed, value : Int}
type Action = Init Time | Generate
init : (Model, Effects Action)
init = (Model (initialSeed 42) 0, Effects.tick Init)
modelFromSeed : Seed -> (Model, Effects Action)
modelFromSeed seed =
let
(value', seed') = generate (int 1 1000) seed
in
(Model seed' value', Effects.none)
update : Action -> Model -> (Model, Effects Action)
update action model =
case action of
Init time ->
modelFromSeed (initialSeed (round time))
Generate ->
modelFromSeed model.seed
view : Signal.Address Action -> Model -> Html
view address model =
div []
[ text ("Current value: " ++ (toString model.value))
, br [] []
, button [onClick address Generate] [text "New Value"]
]
app : StartApp.App Model
app = StartApp.start
{ init = init
, update = update
, view = view
, inputs = []
}
main : Signal Html
main = app.html
port tasks : Signal (Task Never ())
port tasks = app.tasks