且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

产生唯一的随机数

更新时间:2023-02-05 17:09:30

好问题。这里有两个部分:
-生成随机数,和
-将所有内容连接起来

Great question. There are two parts here: - generating random numbers, and - wiring this all up

对于前者,您将需要Random库,稍加检查便会导致您进入

You will need the Random library for the former, and a little inspection will lead you to something like

get15Randoms = Random.generate OnRandomNumbers <| Random.list 5 (int 0 100)

此类型为 Cmd Msg -这是一个异步操作,将在消息上返回。

This has type Cmd Msg - it's an async operation that will return on a Msg.

将其连接起来将经历一系列阶段。您指的是在 init中执行此操作,但这并不是Elm在这里为您工作的方式。在init函数中,您可以启动json请求。然后您将需要类似

Wiring it up will be a series of stages. You refer to doing it in 'init' but that's not how Elm is going to work for you here. In the init function you can start off your json request. Then you'll need something like

init = ( initModel
       , Http.get {url =..., expect = Http.expectJson OnJson yourDecoder} 
       )

update msg model = 
    case msg of 
        OnJson (Ok data) ->
            -- attach json
            ( {model | data = data }, get15Randoms )
        OnRandomNumbers ints ->
            ( { model | ints = ints }, Cmd.none )

json回来后,您可以附加它,并使用该更新的迭代启动您的随机数请求,然后在后续迭代中捕获结果

In other words, once the json comes back you can attach that, and use that iteration of the update to launch your random number request, and then catch the result in a subsequent iteration