模組 Type.Id

module Id: sig .. end

類型識別符。

類型識別符是一個表示類型的數值。給定兩個類型識別符,可以測試它們是否 相等,以證明它們表示相同的類型。請注意:

  • 不相等的識別符並不意味著不相等的類型:一個給定的類型可以由多個識別符表示。
  • 類型識別符可以被封送(marshalled),但在解除封送(unmarshalling)時會獲得一個新的、不同的身份,因此相等性會遺失。

請參閱使用範例 example


類型識別符

type !'a t 

類型為 'a 的識別符的類型。

val make : unit -> 'a t

make () 是一個新的類型識別符。

val uid : 'a t -> int

uid idid 的執行期唯一識別符。

val provably_equal : 'a t -> 'b t -> ('a, 'b) Type.eq option

provably_equal i0 i1 如果識別符 i0 等於 i1,則為 Some Equal,否則為 None

範例

以下展示如何使用類型識別符來實現一個簡單的異質鍵值字典。與 Map 的值其鍵映射到單一、同質的數值類型不同,此字典可以將不同類型的數值與每個鍵關聯。

(** Heterogeneous dictionaries. *)
module Dict : sig type t
  (** The type for dictionaries. *)
type 'a key
  (** The type for keys binding values of type 'a. *)
val key : unit -> 'a key
  (** key () is a new dictionary key. *)
val empty : t
  (** empty is the empty dictionary. *)
val add : 'a key -> 'a -> t -> t
  (** add k v d is d with k bound to v. *)
val remove : 'a key -> t -> t
  (** remove k d is d with the last binding of k removed. *)
val find : 'a key -> t -> 'a option
  (** find k d is the binding of k in d, if any. *)
end = struct type 'a key = 'a Type.Id.t type binding = B : 'a key * 'a -> binding type t = (int * binding) list let key () = Type.Id.make () let empty = [] let add k v d = (Type.Id.uid k, B (k, v)) :: d let remove k d = List.remove_assoc (Type.Id.uid k) d let find : type a. a key -> t -> a option = fun k d -> match List.assoc_opt (Type.Id.uid k) d with | None -> None | Some (B (k', v)) -> match Type.Id.provably_equal k k' with | Some Type.Equal -> Some v | None -> assert false end