Optional argument in method with ocaml


I am facing a problem with an optional argument in a method class.

Let me explain. I have a pathfinding class graph(in the Wally module) and one of its methods shorthestPath. It uses an optional argument. The fact is that I call (with an optional argument or not) this OCaml method returns a conflict of the type:

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

whereas type shorthestPath:

method shorthestPath : ?src:string -> string -> string list

I also tried to use the option format for an optional argument:

method shorthestPath ?src dst =
  let source = match src with
    | None -> currentNode
    | Some node -> node
  in 
  ...

Only when I remove the optionnal argument does OCaml stop offending me.

Thank you in advance for your help :)

+1
source share
1 answer

, , :

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. *)

( 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

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)

, , .

. 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)

. !

: OCaml , .

+6

All Articles