Search code examples
fieldrecordelm

How to write a generic function that updates fields of a Record


Consider

type alias Rec = { a: Int, b: Int, c:Int }
updateRec r aVal            = { r|a = aVal } 
updateRec2 r aVal bVal      = { r|a = aVal, b= bVal } 
updateRec3 r aVal bVal cVal = ...

How to generalize updateRec and updateRec2... into one function?


Solution

  • Here's a better way of doing the same thing:

    updateA : Int -> Rec -> Rec
    updateA x rec = { rec | a = x }
    
    -- Similarly for b, c
    

    Now you can do the following, supposing you already have a value rec : Rec you want to update:

    myUpdatedRec : Rec
    myUpdatedRec =
      rec 
      |> updateA 7
      |> updateB 19
    

    You can now update an arbitrary number of fields by stringing together |> updateX ....