首页 > 解决方案 > 通用列表类型的 ocaml 类型错误 (ide * 'a)

问题描述

我正在编写一个 OCaml 解释器,我会检查成对列表中是否有重复项。

type exp = ... | Dict of (ide * exp) list | AddPair of exp * (ide * exp) list;;
type evT = ... | DictVal of (ide * evT) list


Dict(pairs) -> 
             if invariant pairs then DictVal(evalDictList pairs r) 
             else failwith("The Dictionary has multiple copy of the same key")|

AddPair(dict, newpair) ->
             (match (eval dict r) with
                DictVal (oldpairs) -> let evalnewpair = evalDictList newpair r in
                                                if invariant (evalnewpair@oldpairs) then DictVal(oldpairs@evalnewpair)
                                                else failwith ("A new key has the same value as another already inserted")|
                            _ -> failwith ("not a dictionary"))|

and evalDictList (pairs : (ide * exp) list) (r : evT env) : (ide * evT) list = match pairs with
                [ ] -> [ ] |
                (key,value) :: other -> (key, eval value r) :: evalDictList other r;;

和不变量:

and invariant (pairs : (ide * 'a) list) : bool = match pairs with
        [ ] -> true |
        (key,value) :: other -> if lookfor key other then invariant other else false

错误: 此表达式具有类型 (ide * evT) 列表,但预期的表达式类型为 (ide * exp) 列表类型 evT 与类型 exp 不兼容

在“Dict”不变量中使用 (ide * exp) 列表,而在“AddPair”不变量中将获得 evalnewpair@oldpairs,其中 evalnewpair 具有类型 (ide * evT) 和 oldpairs (ide * evT)。

标签: expressionocamltypeerrorinterpreter

解决方案


如果invariant是相互递归函数定义的一部分,则需要明确使用通用量化:

and invariant: 'a.  (ide * 'a) list -> bool = fun l -> ...

invariant在您的情况下,从相互递归块中分离出来可能更简单。


推荐阅读