在 Elm 中使用数字作为类型
Using numbers as types in Elm
我正在学习 elm,我正在尝试使用类型来更好地描述我的领域。但我被困在这里:我不能使用数字文字作为 types/type 别名?有 "elmish way" 可以做到这一点吗?
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
}
(艾莉 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
.
的参数
我正在学习 elm,我正在尝试使用类型来更好地描述我的领域。但我被困在这里:我不能使用数字文字作为 types/type 别名?有 "elmish way" 可以做到这一点吗?
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
}
(艾莉 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
.