Types ocaml中的类型错误-此表达式具有类型(string*';a)列表,但与类型exp一起使用
一、 我有一个简单的ocaml程序Types ocaml中的类型错误-此表达式具有类型(string*';a)列表,但与类型exp一起使用,types,ocaml,Types,Ocaml,一、 我有一个简单的ocaml程序 type tree = Node of string * exp * tree * tree | Empty and exp = Etree of tree | EInt of int | List of (string*exp);; let rec evalNode....... and rec eval (e:exp) = (match e with | EInt _ -> e | Etree(tree) ->
type tree = Node of string * exp * tree * tree | Empty
and exp = Etree of tree | EInt of int | List of (string*exp);;
let rec evalNode.......
and rec eval (e:exp) =
(match e with
| EInt _ -> e
| Etree(tree) -> (match tree with
| Empty -> []
| Node(s,i,t1,t2) -> (evalNode (tree)) )
)
evalNode:tree->(string*exp)list=fun
评估:经验->经验=乐趣
但返回此错误,但我不理解这意味着什么,web中没有太多关于ocaml的信息:
此表达式具有类型(字符串*'a)列表,
但是与类型exp一起使用
Etree内部有一个类型节点,类型树也是,所以我可以用这个值调用evalNode,因为它需要一个树类型
evalNode返回(string*exp)的列表,但它是一个exp,因此eval可以返回它
evalNode返回(string*exp)的列表,但它是一个exp
这是您的错误:
string*exp
的列表不是exp
;编译器无法猜测您打算应用构造函数List
从此列表构建exp
(如果List
的正确定义恰好是List of(string*exp)List
)。Ocaml中的任何表达式都必须返回单个类型。因此,例如,您不能编写类似于如果a>b然后“a”else 7
的内容,因为它不知道该表达式的类型是string还是int
在您的eval函数中,没有任何意义,您正在执行类似的操作。当e
是EInt
时,将触发第一个匹配选项,并返回类型为exp
的e
。当e
是一个Etree(空)
时,它触发第二个匹配选项,该选项依次调用第二个匹配语句,并在其中触发第一个匹配选项,返回[]
,该列表的类型为'a list
(表示未知类型的列表)。当e
是一个Etree(节点(s,i,t1,t2))
时,第二个match语句中的第二个匹配选项被触发,返回evalnode(tree)
,我们从您编写的类型(string*exp)列表中知道该选项
因此,内部匹配本身是很好的,因为它可以统一通用列表和特定列表。但是组合外部匹配是有问题的,因为第一种情况返回一个exp
,第二种情况返回一个(string*exp)列表
,所以它不知道表达式应该具有什么类型。我不知道为什么错误显示为(string*'a)list
,而不是(string*exp)list
,但我怀疑您可以在不必解决这个问题的情况下解决问题
我还要注意的是,您有一个构造函数List of(string*exp)
,其子类型不是List。你可能希望这是List of(string*exp)List
,然后让你的内部匹配返回List([])
和List(evalNode(tree))
,但这只是一个猜测。我想你可能会把List of(string*exp)
和(string*exp)List混为一谈,我相信@glennsl已经搞定了,但是没有错误源的位置,没有实际的代码,我们只能猜测您的问题!