One advantage of Reason ML over JavaScript is that it provides a Map
type that uses structural equality rather than reference equality.
However, I cannot find usage examples of this.
For example, how would I declare a type scores
that is a map of strings to integers?
/* Something like this */
type scores = Map<string, int>;
And how would I construct an instance?
/* Something like this */
let myMap = scores();
let myMap2 = myMap.set('x', 100);
The standard library
Map
is actually quite unique in the programming language world in that it is a module functor which you must use to construct a map module for your specific key type (and the API reference documentation is therefore found underMap.Make
):There are other data structures you can use to construct map-like functionality, particularly if you need a string key specifically. There's a comparison of different methods in the BuckleScript Cookbook. All except
Js.Dict
are available outside BuckleScript. BuckleScript also ships with a new Map data structure in its beta standard library which I haven't tried yet.If you're just dealing with a
Map<string, int>
, Belt'sMap.String
would do the trick.The ergonomics around the Belt version are a little less painful, and they're immutable maps to boot! There's also
Map.Int
within Belt. For other key types, you'll have to define your own comparator. Which is back to something similar to the two step process @glennsl detailed above.