PositiveGuy
PositiveGuy

Reputation: 20162

Updating a Specific Item in a List

Given an elm list like:

twoDimensionalList =
    [ [ 'U', 'U', ' ' ]
    , [ ' ', ' ', ' ' ]
    , [ ' ', ' ', ' ' ]
    ]

How can I update the ' ' in the first row with 'U' within an Elm List? I do not want to use an array I want to figure out how to do this with a List. I've already done the convert List to array and use set. I'm trying to learn how I'd update at a certain element in a list this time.

I started to think about how I might do this but just can't get there:

row1 =
   take 0 twoDimensionalList

row1Updated =
   indexedMap \i row1 -> if i == 2 then --somehow update this item in the map with 'U'

Upvotes: 0

Views: 302

Answers (1)

glennsl
glennsl

Reputation: 29106

For this particular scenario, I would just pattern match on the list, bind the parts I want to preserve to variables, then reconstruct it with my replacement value:

case twoDimensionalList of
    [ a, b, _ ] :: tail ->
        [ a, b, 'U' ] :: tail

    _ ->
        twoDimensionalList

Basically, the :: operator (called "cons") will match or bind the first element (called "head") on the left of it, and the rest of the list (the "tail") on the right. So "a" :: ["b", "c"] will match the list ["a", "b", "c"].

The list literal syntax ([...]) in a pattern will match a list of exactly that size. So the [a, b, _] :: tail will match a list with the first ("head") element itself being a three-element list where the first two elements are bound to the variables a and b and the third element, which we're going to replace, is ignored. The rest of the outer list is then bound to tail.

The list is then reconstructed using pretty much the same syntax. The list literal syntax I'm sure you're familiar with, and the cons operator (::) works similarly to its pattern form, adding the element on the left to the list on the right, e.g. "a" :: ["b", "c"] will return the list ["a", "b", "c"]

Upvotes: 3

Related Questions