List 使用递归创建树

List 使用递归创建树,list,recursion,tree,functional-programming,ocaml,List,Recursion,Tree,Functional Programming,Ocaml,我试图从OCAML中的int列表创建一个树。我对函数式编程非常陌生。这是我目前的职能: let rec theList (lst : int list) = match lst with | [] -> Empty | h::t -> insert Empty h::theList List.tl lst 当insert是一个创建节点并将h值放入节点的函数时。我尝试遍历列表,但在使用参数调用insert后的冒号处,我得到错误:“错误:变量类型bstTree没有构造函数

我试图从OCAML中的int列表创建一个树。我对函数式编程非常陌生。这是我目前的职能:

let rec theList (lst : int list) = 
 match lst with 
  | [] -> Empty
  | h::t -> insert Empty h::theList List.tl lst
当insert是一个创建节点并将h值放入节点的函数时。我尝试遍历列表,但在使用参数调用insert后的冒号处,我得到错误:“错误:变量类型bstTree没有构造函数::”因为这是我定义为的类型:

type bstTree = Empty | bstTree * Node of int * bstTree

从广义上讲,我所要做的就是在列表中递归,并对列表中的每个int调用insert。我已经为此工作了一段时间,所以非常感谢您的帮助,谢谢

您的代码有很多问题(如果您刚刚开始,这是意料之中的)

首先,您的类型定义在语法上无效:

# type bstTree = Empty | bstTree * Node of int * bstTree;;
Error: Syntax error
最有可能的情况是,您想要的东西更像这样:

type bstTree = Empty | Node of bstTree * int * bstTree
insert Empty h (fromList List.tl lst)
其次,您正在定义一个名为
theList
的函数,但在该函数中,您调用了名为
fromList
的函数。我怀疑这些应该是同一个名字

第三,不需要调用
List.tl
,因为您已经在名称
t
下匹配了列表的尾部

第四,表达式中需要更多的括号。一个好的起点可能是这样的:

type bstTree = Empty | Node of bstTree * int * bstTree
insert Empty h (fromList List.tl lst)

正如编译器所指出的,您不能将构造函数
应用于
bstree
类型的值。
::
构造函数仅用于从一个元素和另一个(较小的)列表构建列表。

您的代码存在许多问题(如果您刚刚开始,这是意料之中的)

首先,您的类型定义在语法上无效:

# type bstTree = Empty | bstTree * Node of int * bstTree;;
Error: Syntax error
最有可能的情况是,您想要的东西更像这样:

type bstTree = Empty | Node of bstTree * int * bstTree
insert Empty h (fromList List.tl lst)
其次,您正在定义一个名为
theList
的函数,但在该函数中,您调用了名为
fromList
的函数。我怀疑这些应该是同一个名字

第三,不需要调用
List.tl
,因为您已经在名称
t
下匹配了列表的尾部

第四,表达式中需要更多的括号。一个好的起点可能是这样的:

type bstTree = Empty | Node of bstTree * int * bstTree
insert Empty h (fromList List.tl lst)

正如编译器所指出的,您不能将构造函数
应用于
bstree
类型的值。
构造函数仅用于从一个元素和另一个(较小的)列表构建列表。

感谢您的帮助。我做了您建议的必要更改,在以下行:
h::t->insert Empty h(fromList.tl lst)
我现在收到一个错误,错误是:“错误:此函数的类型为bstree->int->bstree,它应用于太多参数;可能您忘记了一个“;”。insert:bstree→ int→ 我真的不明白这个问题@杰弗里斯感谢你的帮助。我做了您建议的必要更改,在以下行:
h::t->insert Empty h(fromList.tl lst)
我现在收到一个错误,错误是:“错误:此函数的类型为bstree->int->bstree,它应用于太多参数;可能您忘记了一个“;”。insert:bstree→ int→ 我真的不明白这个问题@杰弗里