On The Net Again
On The Net Again

Reputation: 305

Updating a record in Elm

NOTE: This is my first time ever looking at Elm and I just learned about its existence last week by accident.

When you update a record, are you really updating a record or just creating a new one.

> { bill | name = "Nye" }
{ age = 57, name = "Nye" }

> { bill | age = 22 }
{ age = 22, name = "Gates" }

I would expect:

> { age = 22, name = "Nye" }

Since there were two updates done on 'bill'.

Reading from the Elm language site, I know there aren't destructive updates. A new object (with the same name?) is created and shares the fields that weren't changed of the old(er) object. But from these examples, it doesn't seem like 'bill' is being updated at all. It looks more like 'bill' is being copied, that copy is being updated, and a new record called 'anonymous Will' is being created. A completely new record.

So what am I misunderstanding here?

Upvotes: 3

Views: 2529

Answers (2)

Eric
Eric

Reputation: 1521

You are creating a new record.

The docs you're reading say just as much:

In other words, when we update some fields of bill we actually create a new record rather than overwriting the existing one.

The examples they give are in the context of the Elm REPL. In those examples, bill is assigned a value only once and does not change. The updates are not assigned to variables, and the results are printed to the screen.

In an Elm file, updated records are usually the output of functions. The update function in Elm Architecture Tutorial Example 2 demonstrates this well. I've simplified the function below (at the expense of modularity and scalability).

type alias Model =
  { topCounter : Int
  , bottomCounter : Int
  }

type Action
  = Reset
  | IncTop
  | DecTop
  | IncBottom
  | DecBottom

update : Action -> Model -> Model
update action model =
  case action of
Reset ->
  Model 0 0
IncTop ->
  { model | topCounter = model.topCounter + 1 }
DecTop ->
  { model | topCounter = model.topCounter - 1 }
IncBottom ->
  { model | bottomCounter = model.bottomCounter + 1 }
DecBottom ->
  { model | bottomCounter = model.bottomCounter - 1 }

Upvotes: 0

timothyclifford
timothyclifford

Reputation: 6959

It looks like you're working in the Elm REPL? Doesn't look like you're assigning the output of your first update to anything. This means when you do your second update on age, you're still just making a copy of the first object, which has the same name, rather than the second object you named Nye.

-- Create Bill Gates
billGates = { age = 100, name = "gates" }

-- Copy to Bill Nye
billNye = { bill | name = "Nye" }

-- Copy to a younger Bill Nye
youngBillNye = { billNye | age = 22 }

Make sense?

Upvotes: 4

Related Questions