Updating records with similar fields in Elm

June 29, 2017 - 2 minute read -
Programming Elm

While working in Elm, I came across the problem of updating records that had similar fields but I had to write a function for each type due to lack of type classes.

Lets say we have the following two records defined in our app and we want to update the error field in both these records with a String type.

type alias UserForm =
  { name: String
  , error: Maybe String

type alias VehicleForm =
  { registration: String
  , error: Maybe String

Before I found this trick, I had to write two functions, one for each record.

addErrorToUserForm: UserForm -> String -> UserForm
addErrorToVehicleForm: VehicleForm -> String -> VehicleForm

The solution was hidden in Richard Feldman’s amazing open source application.

addError: { model | error: Maybe String } -> String -> { model | error: Maybe String }
addError record message =
  { record | error = Just message}

Great, isn’t it. I just love Elm, even with all its shortcomings :)