Update subtypes in the update function

Let’s say I have a model that looks something like this:

type alias MySubmodel=
    { x: Int
      y: int
    }

type alias MyModel= {
    a: String,
    b: MySubmodel 
 }

How can I in the update function update x for example?

Doing either

{model | b | x = newVal}
{model | b.x = newVal}

returns an error. Is there even a way to do it?

1 Like

I just gave this a spin in elm repl and it worked out alright. :slight_smile:

type alias MySubmodel =
    { x: Int
    ,  y: Int
    }

type alias MyModel =
  {  a: String
  ,   b: MySubmodel
   }
model = { a= "hello", b = {x=1, y=2}}

let
   b = model.b
in
   { model | b = { b | x = 7 } }

{ a = "hello", b = { x = 7, y = 2 } }
    : { a : String, b : { x : number, y : number1 } }

I would have used “model.b” on the interior curly brace except that appeared to confuse the parser, so I just used a let statement to give it a simpler name first instead. :slight_smile:

Is this roughly what you’re looking for?

1 Like

Yes! Thank you. I haven’t yet quite figured out the let … in keywords. Also I didn’t nest 2 curly braces. But with your approach it should work :slight_smile:

You could also do it like this:

{ model | b = model.b |> (\b -> { b | x = newVal } ) }

I find this to be both more compact and clear than the alternatives, and you can easily extract the nested update if you want.

3 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.