我有递归函数,当然是树的分支
type tree = Node of bool ref * (char * tree) list ref
type cours= tree ->char list -> char list* char list * tree
let cours t word=
let rec cours_tree t word l1 l2=match t,word with
| Noeud(r,n),[] -> Noud (r,n), l1 , l2
| Noeud (r,n),x::h when (List.mem_assoc x !n) ->
x::l1,cours_tree (List.assoc x !n) h l1 l2
| Noeud (r,{content=(c,b)::n),x::h ->
x::l2,cours_tree (List.assoc x b) h l1 l2
in
cours_tree t word [] []
我希望这能够从给定的字符列表中浏览树,并返回到达的子树,字符列表和无法到达的列表; 但是我收到了一个错误:
Error: This expression has type char list * 'a
but an expression was expected of type 'a
The type variable 'a occurs inside char list * 'a#
我不知道我的问题在哪里。
答案 0 :(得分:0)
有很多问题:
Noud
和Noeud
是未定义的构造函数。{
。ref
不匹配
match
案例会返回tree * list * list
但其他案例
返回无限类型。ref
。 content
应为contents
。List.assoc
中输入错误。 b
是tree
,但预计会出现(char * 'a) list
类型的表达式。以下代码修复了问题并在编译时,但由于您提供的问题描述不完整而无法正常运行:
type tree = Node of bool ref * (char * tree) list ref
type cours = tree -> char list -> char list * char list * tree
let cours t word =
let rec cours_tree t word l1 l2 =
match t, word with
| Node (r, n), [] -> Node (r, n), l1, l2
| Node (r, n), x::h when List.mem_assoc x !n ->
let t', l1', l2' = cours_tree (List.assoc x !n) h l1 l2 in
t', x::l1', l2'
| Node (r, {contents = (c, b)::n}), x::h ->
let t', l1', l2' = cours_tree (List.assoc x n) h l1 l2 in
t', l1', x::l2'
in cours_tree t word [] []