Phi*_*kni 1 methods ocaml class optional-arguments
我遇到了方法类中的可选参数的问题.
让我解释.我有一个寻路类graph(在Wally模块中)和一个他的方法shorthestPath.它使用可选参数.事实是,当我调用(使用或不使用可选参数)时,此方法OCaml返回类型冲突:
Error: This expression has type Wally.graph
but an expression was expected of type
< getCoor : string -> int * int;
getNearestNode : int * int -> string;
shorthestPath : src:string -> string -> string list; .. >
Types for method shorthestPath are incompatible
Run Code Online (Sandbox Code Playgroud)
而shorthestPath类型是:
method shorthestPath : ?src:string -> string -> string list
Run Code Online (Sandbox Code Playgroud)
我也尝试使用选项格式作为可选参数:
method shorthestPath ?src dst =
let source = match src with
| None -> currentNode
| Some node -> node
in
...
Run Code Online (Sandbox Code Playgroud)
只有在我删除optionnal参数的情况下,OCaml停止侮辱我.
预先感谢您的帮助 :)
目前还不是很清楚你的情况如何,但我想以下几点:
let f o = o#m 1 + 2
let o = object method m ?l x = match l with Some y -> x + y | None -> x
let () = print_int (f o) (* type error. Types for method x are incompatible. *)
Run Code Online (Sandbox Code Playgroud)
使用站点(这里是定义f),从其上下文推断出对象的类型.在这里,o : < x : int -> int; .. >.这个方法x的类型是固定的.
o稍后定义的对象独立于参数f且具有类型< m : ?l:int -> int -> int; .. >.不幸的是,这种类型与另一种不相容.
解决方法是为使用站点提供有关可选参数的更多类型上下文:
let f o = o#m ?l:None 1 + 2 (* Explicitly telling there is l *)
let o = object method m ?l x = match l with Some y -> x + y | None -> x end
Run Code Online (Sandbox Code Playgroud)
或者给出以下类型o:
class c = object
method m ?l x = ...
...
end
let f (o : #c) = o#m 1 + 2 (* Not (o : c) but (o : #c) to get the function more polymoprhic *)
let o = new c
let () = print_int (f o)
Run Code Online (Sandbox Code Playgroud)
我认为这更容易,因为事先通常会有一个类声明.
高级使用带有可选参数的函数之间的这种故障也发生在对象之外.OCaml试图很好地解决它,但并不总是可行的.在这种情况下:
let f g = g 1 + 2
let g ?l x = match l with Some y -> x + y | None -> x
let () = print_int (f g)
Run Code Online (Sandbox Code Playgroud)
很好地输入.太好了!
关键规则:如果OCaml无法推断出省略的可选参数,请尝试明确给出一些关于它们的类型上下文.