Search code examples
syntaxrecordcapitalizationpurescript

Can records have capitalized fields?


In purescript, {foo :: Foo} desugars to Record ("foo" :: Foo), as far as my understanding goes. Could I make something like Record ("F" :: Foo)? How would that look in record access syntax? Would thing.F be syntactically valid?


Solution

  • Quoting fields is exactly the way to do it, both in the type:

    type MyRecord = { "Usually impossible field name" :: Boolean }
    

    And in accessors / patterns:

    make :: Boolean -> MyRecord
    make = { "Usually impossible field name": _ }
    
    get :: MyRecord -> Boolean
    get = _."Usually impossible field name"
    
    update :: MyRecord -> Boolean -> MyRecord
    update = _ { "Usually impossible field name" = _ }
    

    Quoting fields this way allows you to name the record fields whatever you want, using caps, symbols, numbers, etc.

    This is a little similar to obj["property"] in JavaScript, but you can only use string literals for the property name rather than arbitrary values.