Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm adding item in a list on update

Tags:

list

elm

I m trying to understand Elm lang, and I m having some problem dealing with the update part of my little app.

Actually, I want that when I click on a button, it adds a new User in a List, something really simple that doesn't have any sense, but I need to understand.

Right now, I m having the following code :

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

And I m having the following error :

-- 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.

In fact what I m currently understanding from the update function is :

  • Take a Msg in the first function that returns a function accepting a User
  • This function (accepting the user) returns a function accepting a List of Users (to make the operation user::userList)
  • This last function returns a List of User and I m done

But I can't get the point where I am wrong in this situation.

Can you help me ?

like image 304
mfrachet Avatar asked Feb 04 '23 15:02

mfrachet


1 Answers

Html.beginnerProgram expects the update function to be of type Msg-> Model -> Model (your Model is named "User" which is no problem). The User you want to add belongs to the "AddUser" union type.

type Msg = AddUser User

This means you pass the new User along with the Msg (so you can use different messages passing different things). To get the new User you can pattern match it in "case"

case msg of
    AddUser newUser ->
        newUser :: userList
like image 87
farmio Avatar answered Feb 12 '23 15:02

farmio