我试图理解Elm lang,我在处理我的小应用程序的更新部分时遇到了一些问题。
实际上,我希望当我点击一个按钮时,它会在列表中添加一个新用户,这个东西非常简单,没有任何意义,但我需要理解。
现在,我有以下代码:
main =
Html.beginnerProgram { model = model, view = view, update = update }
type Msg = AddUser
type alias User =
{
username : String,
firstname: String,
lastname: String
}
model: List User
model =
[]
update: Msg -> User -> List User -> List User
update msg user userList =
case msg of
AddUser ->
user::userList
我遇到以下错误:
-- TYPE MISMATCH ------------------------------------------------------ main.elm
The argument to function `beginnerProgram` is causing a mismatch.
5| Html.beginnerProgram { model = model, view = view, update = update }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Function `beginnerProgram` is expecting the argument to be:
{ ..., update : Msg -> List User -> List User }
But it is:
{ ..., update : Msg -> User -> List User -> List User }
Hint: Problem in the `update` field. I always figure out field types in
alphabetical order. If a field seems fine, I assume it is "correct" in
subsequent checks. So the problem may actually be a weird interaction with
previous fields.
事实上,我目前从更新功能中理解的是:
但在这种情况下我无法理解错误。
你能帮助我吗?
答案 0 :(得分:8)
Html.beginnerProgram期望更新函数的类型为Msg-> Model -> Model
(您的模型名为“User”,这没有问题)。您要添加的用户属于“AddUser”联合类型。
type Msg = AddUser User
这意味着您将新用户与Msg一起传递(因此您可以使用传递不同内容的不同消息)。 要获得新用户,您可以在“案例”
中进行模式匹配case msg of
AddUser newUser ->
newUser :: userList