我正在学习榆树,我正在尝试使用类型来更好地描述我的领域。但是我被困在这里:我不能使用数字文字作为类型/类型别名吗?是否有“ elmish方式”来做到这一点?
module Main exposing (main)
import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
type alias Model =
{ pos : Int }
type Up = 1
type Down = -1
type Direction = Up | Down
type Msg
= Go Direction
initialModel : Model
initialModel =
{ pos = 0 }
update : Msg -> Model -> Model
update msg model =
case msg of
Go Up ->
{ model | pos = model.pos + Up }
Go Down ->
{ model | pos = model.pos + Down }
view : Model -> Html Msg
view model =
div []
[ button [ onClick Go Up ] [ text "+1" ]
, div [] [ text <| String.fromInt model.count ]
, button [ onClick Go Down ] [ text "-1" ]
]
main : Program () Model Msg
main =
Browser.sandbox
{ init = initialModel
, view = view
, update = update
}
(ellie link:https://ellie-app.com/7HRDRKHRCFDa1)
为了将Up
和Down
与运算符+
一起使用,它们必须是值,而不是类型–与其他操作数类型相同的值。因此,将它们定义为Int
类型的常量:
up : Int
up = 1
down : Int
down = -1
然后您可以将update
函数编写为:
update : Msg -> Model -> Model
update msg model =
case msg of
Go Up ->
{ model | pos = model.pos + up }
Go Down ->
{ model | pos = model.pos + down }
有关完整的工作代码,请参阅this Ellie。我所做的唯一另一处更改是对按钮的onClick
–必须为onClick <| Go Up
,以告知编译器Up
是Go
的参数,而结果是onClick
的参数。] >