OCaml:设置模块 [英] OCaml: Set modules
问题描述
我想使用OCaml生成数据集并在它们之间进行比较.我看过有关Set.OrderType
,Set.Make
等模块类型的文档,但是我不知道如何初始化集合或以其他方式使用它们.
I want to use OCaml to generates sets of data and make comparisons between them. I have seen the documentation for Module types like Set.OrderType
, Set.Make
, etc, but I can't figure out how to initialize a set or otherwise use them.
推荐答案
使用函数接口定义集合.对于任何给定的类型,必须使用Set.Make
函子为该类型创建一个Set
模块.不幸的是,标准库没有为内置类型定义Set
实例.在大多数简单情况下,使用Pervasives.compare
就足够了.这是适用于int
的定义:
Sets are defined using a functorial interface. For any given type, you have to create a Set
module for that type using the Set.Make
functor. An unfortunate oversight of the standard libraries is that they don't define Set
instances for the built-in types. In most simple cases, it's sufficient to use Pervasives.compare
. Here's a definition that works for int
:
module IntSet = Set.Make(
struct
let compare = Pervasives.compare
type t = int
end )
模块IntSet
将实现Set.S
接口.现在,您可以使用IntSet
模块对集合进行操作:
The module IntSet
will implement the Set.S
interface. Now you can operate on sets using the IntSet
module:
let s = IntSet.empty ;;
let t = IntSet.add 1 s ;;
let u = IntSet.add 2 s ;;
let tu = IntSet.union t u ;;
请注意,您不必将Set.Make
的输入结构明确定义为OrderedType
;类型推断将为您完成工作.另外,您可以使用以下定义:
Note that you don't have to explicitly define the input structure for Set.Make
as an OrderedType
; type inference will do the work for you. Alternatively, you could use the following definition:
module IntOrder : Set.OrderedType = struct
type t = int
let compare = Pervasives.compare
end
module IntSet = Set.Make( IntOrder )
这样的好处是您可以重新使用同一模块来实例化Map
:
This has the advantage that you can re-use the same module to instantiate a Map
:
module IntMap = Map.Make( IntOrder )
使用函子会失去一些通用性,因为元素的类型是固定的.例如,您将无法定义一个函数,该函数采用某种任意类型的Set
并对其执行某些操作. (幸运的是,Set
模块本身在Set
上声明了许多有用的操作.)
You lose some genericity in using functors, because the type of the elements is fixed. For example, you won't be able to define a function that takes a Set
of some arbitrary type and performs some operation on it. (Luckily, the Set
module itself declares many useful operations on Set
s.)
这篇关于OCaml:设置模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!