Dedicated syntax for dict literals

Creating dictionary literals is a bit cumbersome in rescript, especially when you have nested dicts:

Js.Dict.fromArray([("blue", Js.Dict.fromArray([("light", true)]))])

Since there is already a syntax similar for lists (list{}) , what about creating a dedicated syntax for dictionaries like this:

dict{
  "blue" : dict{
    "light" : true
  } 
} 

Having a syntax for element lookup would be nice too, for example:

let blueSetup = colors.["blue"]

Chaining lookups would require some additional mechanisms though since a lookup returns an option.

What do you guys think?

2 Likes

An obvious drawback is that unlike other similar syntaxes you could not pattern match on this syntax which would be confusing.

I think you could get away with a poor man’s DSL:

let fa = Js.Dict.fromArray

fa([("blue", fa([("light", true)]))])

Or even:

MyModule.fromNestedArray([
  ("blue": [("light": true)]),
  ("green": [("light": false)]),
])

Having said that, what’s your use case? Why does it have to be a Dict if you create it like an object literal? (A guess: is it a third-party API?)

Yes that’s what I do meanwhile, but not as readable as a dedicated syntax obviously.
And yes it’s for some JS bindings, but you could have the same syntax for Belt Map for example.

A project I’m working on uses a lot of dicts for interop with JS, and a dedicated syntax would be extremely helpful. FWIW, there’s an open issue about this on the syntax repo: https://github.com/rescript-lang/syntax/issues/179

3 Likes