functional-programming - 如何在 OCaml 中使用 Map/定义实际上是 Map 的类型?

标签 functional-programming ocaml

我将练习在 Ocaml 中使用 Map

我发现Map的用法与ListArray等有很大区别

我知道它正在应用我还没有学过的 functor。但没关系。


这是我的IntMap

module IntMap = Map.Make(struct type t = int let compare = compare end)

那么,现在我可以使用 IntMap 通过 IntMap.add xy map 等来add,对吧?


我有几个问题:

  1. 如何控制 mapvalue 的类型?
  2. 如果我想为我的IntMap 取一个别名类型,我应该怎么做?我可以做 type 'a my_type = 'a list,但是如何做 map
  3. 我发现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/

相关文章:

c - c中的指针和数组

swift - Swift 的 `reduce` 语法有问题

ocaml - 在 Ocaml 中将自定义变量写入和读取到文件

string - 将字符串拆分为字符列表的最简单方法是什么?

scala - 如果数据结构是可折叠的,它是幺半群吗?

functional-programming - ELM 更新模型中的两个字段

haskell - 是否有带有显式子类型的 ADT 名称?

compiler-errors - OCaml 行产生神秘错误

module - 是否有一种简洁/内联的方式来创建 Set 值而不显式命名它们的类型?

list - 使用 fold_left 在 OCaml 中搜索元素