在使用Base的OCaml中,如何构造一个类型为`int * int`的元素的集合? [英] In OCaml using Base, how do you construct a set with elements of type `int * int`?

查看:66
本文介绍了在使用Base的OCaml中,如何构造一个类型为`int * int`的元素的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在F#中,我只想做:

> let x = Set.empty;;
val x : Set<'a> when 'a : comparison

> Set.add (2,3) x;;
val it : Set<int * int> = set [(2, 3)]

我了解到,在OCaml中,使用Base时,我必须提供一个具有比较功能的模块,例如,如果我的元素类型是string

I understand that in OCaml, when using Base, I have to supply a module with comparison functions, e.g., if my element type was string

let x = Set.empty (module String);;
val x : (string, String.comparator_witness) Set.t = <abstr>

Set.add x "foo";;
- : (string, String.comparator_witness) Set.t = <abstr>

但是我不知道如何构造一个具有类型int * int的比较功能的模块.我该如何构造/获得这样的模块?

But I don't know how to construct a module that has comparison functions for the type int * int. How do I construct/obtain such a module?

推荐答案

There are examples in the documentation for Map showing exactly this.

如果您使用他们的PPX,则可以执行以下操作:

If you use their PPXs you can just do:

module IntPair = struct
  module T = struct
    type t = int * int [@@deriving sexp_of, compare] 
  end

  include T
  include Comparable.Make(T)
end

否则,完整的实现是:

module IntPair = struct
  module T = struct
    type t = int * int
    let compare x y = Tuple2.compare Int.compare Int.compare
    let sexp_of_t = Tuple2.sexp_of_t Int.sexp_of_t Int.sexp_of_t
  end

  include T
  include Comparable.Make(T)
end

然后您可以使用此模块创建一个空集:

Then you can create an empty set using this module:

let int_pair_set = Set.empty (module IntPair)

这篇关于在使用Base的OCaml中,如何构造一个类型为`int * int`的元素的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆