【问题标题】:ocaml type error with generic list type (ide * 'a)通用列表类型的 ocaml 类型错误 (ide * 'a)
【发布时间】:2019-01-10 11:21:04
【问题描述】:

我正在编写一个 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”中,在“AddPair”中使用 (ide * exp) 的列表 invariant 将得到 evalnewpair@oldpairs ,其中 evalnewpair 具有类型 (ide * evT) 和 oldpairs (ide * evT)。

【问题讨论】:

    标签: expression ocaml typeerror interpreter


    【解决方案1】:

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

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

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

    【讨论】:

    • 但这会得到相同的参数,问题是我给不变量作为参数
    • 不,这两种类型的注释是有意义的不同,这种差异在相互递归的函数定义中很重要。另请注意,您应该尝试给出一个完整的示例和确切的错误。
    • 我改了帖子
    • 您的示例仍然不是独立的。但是,在修复漏洞之后,我重申您的问题是不变量上的不精确注释,添加显式通用注释可以修复您提到的错误。
    猜你喜欢
    • 1970-01-01
    • 2018-06-27
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多