OCaml中的Trie数据结构
我正在尝试在OCaml中构建一个:OCaml中的Trie数据结构,ocaml,trie,Ocaml,Trie,我正在尝试在OCaml中构建一个: type ('a, 'b) trie = Nil | Cons of 'a * 'b option * ('a, 'b) trie list;; (* find place to insert key in a list of tries *) let rec findInsert key x = match x with [] -> Nil | x::xs -> let Cons(k, _, _) = x in
type ('a, 'b) trie = Nil | Cons of 'a * 'b option * ('a, 'b) trie list;;
(* find place to insert key in a list of tries *)
let rec findInsert key x =
match x with
[] -> Nil
| x::xs -> let Cons(k, _, _) = x in
if key = k then x else findInsert key xs;;
(* inser pair in a trie *)
let rec insert ( key, value ) trie =
match trie with
Nil -> Cons(key, value, [])
| t -> let Cons(k, v, trieList) = t and
subTree = insert (key, value) (findInsert key trieList) and
newSubTree = subTree::trieList in
Cons(k, v, newSubTree);;
但这给了我以下错误:
val findInsert : 'a -> ('a, 'b) trie list -> ('a, 'b) trie = <fun>
File "trie.ml", line 15, characters 54-62:
Error: Unbound value trieList
但当我试着运行它时,我得到了以下结果:
# let t = Cons(3, Some 4, []);;
val t : (int, int) trie = Cons (3, Some 4, [])
# insert (4, Some 5) t;;
Error: This expression has type (int, int) trie/1017
but an expression was expected of type (int, int) trie/1260
这些数字代表什么?你不应该使用
让x=。。。和y=。。。在
中,当y
依赖于x
时,由于由唯一的绑定的所有标识符应同时定义。使用让x=。。。让y=。。。而是在
中,确保定义y
时x
将在范围内。
在您的情况下,这将成为:
let Cons(k, v, trieList) = t in
let subTree = insert (key, value) (findInsert key trieList) in ...
在使用toplevel时,如果定义同一类型两次,ocaml将看到两种类型,而不仅仅是一种。由于您的两种类型具有相同的名称trie
,因此它们被重命名为trie/1017
和trie/1260
。如果重新编译类型声明,则必须重新编译依赖此类型的所有其他声明,以便它们使用新类型而不是旧类型
另外一句话:你不应该写
match foo with
| a -> let PATTERN = a in
您应该改为使用此选项:
match foo with
| PATTERN ->
谢谢我忘了顺序应该有多重要了。如果对你现有问题的回答引发了一个新问题,请在另一篇文章中提问。在同一篇文章中问这个问题意味着好答案变成了坏答案。另外,你的第二个问题可能永远不会得到回答,因为每个人都已经看过你的帖子了。
match foo with
| PATTERN ->