Search code examples
mergerecordelm

Merge model with extensible record in Elm 0.19


I define an extensible record

type alias Saved a =
  { a
    | x : Int
    , y : String
  }

and a Model based on that:

type alias Model =
  Saved { z : Float }

I then load and decode JSON into a Saved {}:

let
  received =
    Decode.decodeValue savedDecoder json |> Result.toMaybe
in
(Maybe.map
  (\r ->
    { model
    | x = r.x
    , y = r.y
    }
  )
  received
  |> Maybe.withDefault model

Is there any way to merge the existing model with the received extensible record that does not involve copying each field individually, similar to the ES6 Object.assign function?


Solution

  • That's the way it's done. Optionally, you can pattern match a parameter:

    Maybe.map
      (\{x, y} ->
        { model
        | x = x
        , y = y
        }
      )