昨天用Elm 实现一个随机数的小练习。网站上给的教程是单个随机数,网站下练习的要求是使用一个Roll按钮控制两个随机数的生成(下面两个Random的分析过程跟着标号走)
单个Random代码如下:
-- Read more about this program in the official Elm guide:
-- https://guide.elm-lang.org/architecture/effects/random.html
import Html exposing (..)
import Html.Events exposing (..)
import Random
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ dieFace : Int
}
init : (Model, Cmd Msg)
init =
(Model 1, Cmd.none)
-- UPDATE
type Msg
= Roll
| NewFace Int
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Roll ->
(model, Random.generate NewFace (Random.int 1 6))
NewFace newFace ->
(Model newFace, Cmd.none)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h1 [] [ text (toString model.dieFace) ]
, button [ onClick Roll ] [ text "Roll" ]
]
两个Random显示代码如下:
-- Read more about this program in the official Elm guide:
-- https://guide.elm-lang.org/architecture/effects/random.html
import Html exposing (..)
import Html.Events exposing (..)
import Random exposing (..)
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ dieFace1 : Int
, dieFace2 : Int
}
1、--一开始的想法就是更改这里,因为从单个Random的view模块可以看出,这个结果是以dieFace来体现的,那么要想
有两个Random,一定得有两个dieface,但是如果简单的使用同样的dieface,得到的两个random的值必然是一样的,那么这个练习就没有任何意义,所以通过增加一个dieFace2来进行输出。
init : (Model, Cmd Msg)
init =
(Model 1 1, Cmd.none)
2、--但是这个时候init就会报错,错误的内容大致是,定义init的时候的结构为int->model,但是在init赋值的时候却是model,我们知道这个init是初始化的意思,所以分析,增加了dieFace的个数,初始化的时候却只给一个进行了初始化,这是不对的。于是尝试将Model 1,改为Model 1 1, 这个时候这里的错误就没有了,报错出现在了别的地方
-- UPDATE
type Msg
= Roll
| NewFace ( Int , Int )
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Roll ->
(model, Random.generate NewFace (pair (Random.int 1 6) (Random.int 1 6)) )
NewFace (newFace1, newFace2) ->
(Model newFace1 newFace2, Cmd.none)
3、--现在报错出现在了这个地方,意思是在Model的定义是Int->Model,但是这里Model却是Model,仔细分析这句错误以及对应的代码可以发现,在单个Random中,Model只有一个值,将值赋值给Model就相当于将值赋值给dieface,但是我们多加了一个dieface,得到的Int值却只有一个。
这个时候的问题就有两个了,首先,如何同时执行两次Random.int,第二执行两次Random.int后得到的值如何赋值给Model 中的两个值。一度陷入僵局。无计可施的时候想起在GitHub上找相似的代码,找到了一个做两个图片的代码。仿照格式给Model赋值,编译通过了
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h1 [] [ text (toString model.dieFace1) ]
, h1 [] [ text (toString model.dieFace2) ]
, button [ onClick Roll ] [ text "Roll" ]
]
(注:Elm使用的人比较少,网上能找到的资源也比较少,如果在刚才的分析过程中有什么说的不对的地方,希望大家能留言告诉我,同时也希望自己在学习Elm中的一些问题以及解决方案能够帮助后来想学习Elm的同学,让Elm被越来越多的人接收)