我将练习在 Ocaml 中使用 Map
。
我发现Map
的用法与List
、Array
等有很大区别
我知道它正在应用我还没有学过的 functor
。但没关系。
这是我的IntMap
module IntMap = Map.Make(struct type t = int let compare = compare end)
那么,现在我可以使用 IntMap
通过 IntMap.add xy map
等来add
,对吧?
我有几个问题:
- 如何控制
map
中value
的类型? - 如果我想为我的
IntMap
取一个别名类型,我应该怎么做?我可以做type 'a my_type = 'a list
,但是如何做map
? - 我发现
IntMap
就像List
,它们实际上都是模块
。但是List
有一个list
的类型,那map
呢?
最佳答案
问:
How do I control the type of value in the map?
您不需要(不需要),'a IntMap.t
是一个参数化类型,它包含 'a
类型的值。因此,单个模块 IntMap
可用于从 int 到 int、从 int 到 bool、从 int 到函数......(当然,单个映射值只能包含单一类型的绑定(bind))。此外,没有理由试图限制 IntMap.empty
的类型,就像没有理由强制 []
为 以外的任何类型一样'一个列表
。
问:
If I want a alias type for my IntMap, what should I do? I can do type 'a my_type = 'a list, but how to do for map?
这样:
type 'a imap = 'a IntMap.t
问:
I find that IntMap is like List and both of them are actually modules. But List has a type of list, what about the map?
这是Intmap.t
。
关于functional-programming - 如何在 OCaml 中使用 Map/定义实际上是 Map 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15809984/