Class 简单OCaml数据结构因未绑定参数错误而失败

Class 简单OCaml数据结构因未绑定参数错误而失败,class,types,polymorphism,ocaml,Class,Types,Polymorphism,Ocaml,我在OCaml中有一个非常基本的类: class handler rule callback methods = object(self) method matches test_string test_method = let r = Str.regexp rule in match Str.string_match r test_string 0 with | false -> false

我在OCaml中有一个非常基本的类:

class handler rule callback methods =
    object(self)
        method matches test_string test_method =
            let r = Str.regexp rule in
            match Str.string_match r test_string 0 with
            | false -> false
            | true -> methods = [] || List.exists (fun nth_method -> nth_method = test_method) methods
    end
但是我无法编译它(文件是handler.ml):


这对我来说没有意义,因为通过我的比较,我似乎很明显地期望
test\u method
methods
的任何元素都是相同的类型。此外,类型系统显然看到它们都是类型
'b
,那么为什么会有问题呢?(请注意,
方法是一个字符串列表。)

让我们将此示例缩小为一个较小的示例,但有相同的问题:

# class c things = object(self) method m thing = List.mem thing things end;;
Error: Some type variables are unbound in this type:
         class c : 'a list -> object method m : 'a -> bool end
       The method m has type 'a -> bool where 'a is unbound
请注意,错误与未绑定的类型变量有关,而不是类型不匹配

这个问题与类定义有关。如果定义独立对象,则可以:

fun things -> object(self) method m thing = List.mem thing things end;;
- : 'a list -> < m : 'a -> bool > = <fun>
您可以验证与此类对应的类型是否为带一个参数的参数化类型:

# type 'a t = 'a c;;
type 'a t = 'a c
您编写的
methods
应该是一个字符串列表,但在您编写的代码中,没有任何约束它。如果要限制定义,则需要添加类型注释(一旦编写了更多将
方法
约束为字符串列表的代码,就可以删除该注释)。您可以将类型注释放在任何您喜欢的地方-在
匹配上
,在
测试方法上
,在
方法上

# class c (things : string list) = object(self) method m thing = List.mem thing things end;;
class c : string list -> object method m : string -> bool end

有关更多信息,请参阅。

让我们将此示例缩小为具有相同问题的较小示例:

# class c things = object(self) method m thing = List.mem thing things end;;
Error: Some type variables are unbound in this type:
         class c : 'a list -> object method m : 'a -> bool end
       The method m has type 'a -> bool where 'a is unbound
请注意,错误与未绑定的类型变量有关,而不是类型不匹配

这个问题与类定义有关。如果定义独立对象,则可以:

fun things -> object(self) method m thing = List.mem thing things end;;
- : 'a list -> < m : 'a -> bool > = <fun>
您可以验证与此类对应的类型是否为带一个参数的参数化类型:

# type 'a t = 'a c;;
type 'a t = 'a c
您编写的
methods
应该是一个字符串列表,但在您编写的代码中,没有任何约束它。如果要限制定义,则需要添加类型注释(一旦编写了更多将
方法
约束为字符串列表的代码,就可以删除该注释)。您可以将类型注释放在任何您喜欢的地方-在
匹配上
,在
测试方法上
,在
方法上

# class c (things : string list) = object(self) method m thing = List.mem thing things end;;
class c : string list -> object method m : string -> bool end

有关更多信息,请参阅。

好的,太好了。非常感谢。这很有帮助。好的,很好。非常感谢。这很有帮助。