Home > Mobile >  How to modify an item in a list in Elm?
How to modify an item in a list in Elm?

Time:01-12

I just started learning Elm and I'm a bit confused how to modify an item in a list. This is my structure:

type alias Player =
    { id : Int
    , name : String
    , isActive : Bool
    }

type alias Model =
    { players : List Player
    , newPlayer : Player
    }

So I have a list of Players, and I want to edit a specific Player in the list (for example changing Player with Id = 2 field "isActive" to True). How could I go about this?

CodePudding user response:

One solution is to use List.map:

setIsActiveForPlayer : List Player -> Int -> Bool -> List Player
setIsActiveForPlayer players id isActive =
  let
    update player =
      if player.id == id then
        { player | isActive = isActive }
      else
        player
  in
  players |> List.map update

Another solution performs the iteration “by hand”:

setIsActiveForPlayer : List Player -> Int -> Bool -> List Player
setIsActiveForPlayer players id isActive =
    case players of
        [] ->
            []

        player :: rest ->
            if player.id == id then
                { player | isActive = isActive } :: rest

            else
                player :: setActivePlayer rest id isActive

This should be slightly more efficient because it reuses the tail of the list following the updated player.

CodePudding user response:

As a helper, you can consider using List.Extra.updateIf

newPlayers = players
  |> List.Extra.updateIf (\player -> player.id == 2) (\player -> { player | isActive = True })
  • Related