Search code examples
elm

Elm record shorthand notation


To get better at functional programming in JavaScript, I started leaning Elm.

In JavaScript you have the object shorthand notation:

const foo = 'bar';
const baz = { foo }; // { foo: 'bar' };

I was wondering whether there is something like that in Elm? I'm asking because I have the following model:

type alias Model =
    { title : String
    , description : String
    , tag : String
    , tags : List String
    , notes : List Note
    }


type alias Note =
    { title : String
    , description : String
    , tags : List String
    }

And an update function that upon receiving the AddNote action adds the note to the notes array and clears the inputs:

AddNote ->
            { model | notes = model.notes ++ [ { title = model.title, description = model.description, tags = model.tags } ], title = "", description = "", tag = "" }

I know that in function definitions you can "destructure" records, but I think even in the return type I would have to explicitly type out each key of the record.

AddNote ->
    { model | notes = model.notes ++ [ getNote model ], title = "", description = "", tag = "" }


getNote : Model -> Note
getNote { title, description, tags } =
    { title = title, description = description, tags = tags }

Solution

  • There is not a shorthand record notation similar to JavaScript objects.

    However, a type alias also serves as a constructor function, so you could have something like this:

    getNote : Model -> Note
    getNote { title, description, tags } =
        Note title description tags