eat*_*hil 0 polymorphism ocaml types class
我在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
Run Code Online (Sandbox Code Playgroud)
但是我无法编译它(文件是handler.ml):
File "handler.ml", line 1, characters 6-339:
Error: Some type variables are unbound in this type:
class handler :
string ->
'a -> 'b list -> object method matches : string -> 'b -> bool end
The method matches has type string -> 'b -> bool where 'b is unbound
Run Code Online (Sandbox Code Playgroud)
这对我来说没有意义,因为我期待的比较看起来很明显,test_method而且任何元素都是methods同一类型.此外,类型系统显然看到它们都是类型'b,为什么它有问题?(对于记录,methods是一个字符串列表.)
让我们将此示例缩小为具有相同问题的较小示例:
# 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
Run Code Online (Sandbox Code Playgroud)
请注意,错误是关于未绑定的类型变量,而不是类型不匹配.
问题与类定义有关.如果你定义一个独立的对象,那很好:
fun things -> object(self) method m thing = List.mem thing things end;;
- : 'a list -> < m : 'a -> bool > = <fun>
Run Code Online (Sandbox Code Playgroud)
请注意对象的类型是多态的.类是类型,而不是类型方案.当您尝试定义时c,类型变量'a保持未绑定:类定义在此类型变量中是多态的.因此,您定义的不是具有类型的类,而是一个类型参数化的类族,就像类型方案是在类型上参数化的类型族一样.
Ocaml允许您定义此类参数化类,但您需要显式声明参数:
# class ['a] c (things : 'a list) = object(self) method m thing = List.mem thing things end;;
class ['a] c : 'a list -> object method m : 'a -> bool end
Run Code Online (Sandbox Code Playgroud)
您可以验证与此类对应的类型是带有一个参数的参数化类型:
# type 'a t = 'a c;;
type 'a t = 'a c
Run Code Online (Sandbox Code Playgroud)
你写的methods应该是一个字符串列表,但是在你编写的代码中,没有任何限制它.如果要限制定义,则需要添加类型注释(一旦编写了更多限制methods为字符串列表的代码,就可以删除它).您可以在任何地方放置类型注释 - on matches,on test_method,on 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
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅Ocaml手册§3.10对象 - 参数化类.
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |