How do I declare a map type in Reason ML?

一个人想着一个人 提交于 2019-11-30 18:29:05

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 under Map.Make):

module StringMap = Map.Make({
  type t = string;
  let compare = compare
});

type scores = StringMap.t(int);

let myMap = StringMap.empty;
let myMap2 = StringMap.add("x", 100, myMap);

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's Map.String would do the trick.

module MS = Belt.Map.String;

let foo: MS.t(int) = [|("a", 1), ("b", 2), ("c", 3)|]->MS.fromArray;

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!