如果列表很长,您可能希望使用哈希表而不是列表来存储访问过的单元格并在近乎恒定的时间内执行查找。
让我扩展和修改 Pascal 的代码:
let rec is_cyclic list already_visited =
match list with
Nil -> false
| Cons(h, { contents = t }) ->
V.mem already_visited h ||
is_cyclic t (V.add already_visited h)
V 模块来自以下仿函数应用程序:
module V = Visits.Make (struct type t = int end)
和访问定义如下:
(* visits.ml *)
struct
module Make (X : sig type t end) :
sig
type elt
type t
val create : int -> t
val mem : t -> elt -> bool
val add : t -> elt -> unit
end with type elt = X.t =
struct
module H = Hashtbl.Make (
struct
type t = X.t
let equal = ( == )
let hash = Hashtbl.hash
end
)
type elt = X.t
type t = unit H.t
let create len = H.create len
let mem tbl x = H.mem tbl x
let add tbl x = H.add tbl x ()
end
end
上面的实现是完全安全且面向未来的,但不像基于列表的解决方案那样是多态的。
可以编写一个使用臭名昭著的 Obj 模块的多态版本,如果不了解许多未正式记录的内容,则不应使用该模块。在下面的代码中使用 Obj 对 Hashtbl 模块的实现做出了假设,这些假设在未来不太可能中断,但您会被警告。
也就是说,它是多态的,因此易于使用:
(* visits.mli *)
type 'a t
val create : int -> 'a t
val mem : 'a t -> 'a -> bool
val add : 'a t -> 'a -> unit
(* visits.ml *)
module H = Hashtbl.Make (
struct
type t = Obj.t
(* Warning: using Obj is not pure OCaml. It makes assumptions
on the current implementation of Hashtbl,
which is unlikely to change in incompatible ways
anytime soon. *)
let equal = ( == )
let hash = Hashtbl.hash
end
)
type 'a t = unit H.t
let create len = H.create len
let mem : 'a t -> 'a -> bool = fun tbl x -> H.mem tbl (Obj.repr x)
let add : 'a t -> 'a -> unit = fun tbl x -> H.add tbl (Obj.repr x) ()