如何在 Reason ML 中声明地图类型?
How do I declare a map type in Reason ML?
Reason ML 优于 JavaScript 的一个优点是它提供了一种 Map
类型,该类型使用结构相等性而不是引用相等性。
但是,我找不到这个的用法示例。
例如,我如何声明一个 scores
类型,它是字符串到整数的映射?
/* Something like this */
type scores = Map<string, int>;
我将如何构建一个实例?
/* Something like this */
let myMap = scores();
let myMap2 = myMap.set('x', 100);
标准库 Map
实际上在编程语言世界中非常独特,因为它是一个模块仿函数,您必须使用它来为您的特定键类型构建映射模块(和 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);
您还可以使用其他数据结构来构造 map-like 功能,尤其是当您特别需要字符串键时。还有 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 我还没试过。
如果您只是处理 Map<string, int>
,Belt 的 Map.String
就可以了。
module MS = Belt.Map.String;
let foo: MS.t(int) = [|("a", 1), ("b", 2), ("c", 3)|]->MS.fromArray;
Belt 版本的人体工程学设计不那么痛苦,而且它们是不可变的引导图! Belt 中还有 Map.Int
。对于其他键类型,您必须定义自己的比较器。这又回到了类似于上面详述的两步过程@glennsl 的东西。
Reason ML 优于 JavaScript 的一个优点是它提供了一种 Map
类型,该类型使用结构相等性而不是引用相等性。
但是,我找不到这个的用法示例。
例如,我如何声明一个 scores
类型,它是字符串到整数的映射?
/* Something like this */
type scores = Map<string, int>;
我将如何构建一个实例?
/* Something like this */
let myMap = scores();
let myMap2 = myMap.set('x', 100);
标准库 Map
实际上在编程语言世界中非常独特,因为它是一个模块仿函数,您必须使用它来为您的特定键类型构建映射模块(和 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);
您还可以使用其他数据结构来构造 map-like 功能,尤其是当您特别需要字符串键时。还有 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 我还没试过。
如果您只是处理 Map<string, int>
,Belt 的 Map.String
就可以了。
module MS = Belt.Map.String;
let foo: MS.t(int) = [|("a", 1), ("b", 2), ("c", 3)|]->MS.fromArray;
Belt 版本的人体工程学设计不那么痛苦,而且它们是不可变的引导图! Belt 中还有 Map.Int
。对于其他键类型,您必须定义自己的比较器。这又回到了类似于上面详述的两步过程@glennsl 的东西。