Browse thread
[Caml-list] Question on typing of class/object and optional argument.
-
Nobuyuki Tomizawa
-
Virgile Prevosto
- Olivier Andrieu
-
Virgile Prevosto
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Olivier Andrieu <andrieu@i...> |
| Subject: | Re: [Caml-list] Question on typing of class/object and optional argument. |
Virgile Prevosto [Tuesday 17 December 2002] : > > Hello, > Nobuyuki Tomizawa a écrit: > > > ------------------------------------------------------------ > > class foo s = object > > val str : string = s > > method to_string ?(opt = "" ) () = opt ^ s > > end;; > > > > let l = [new foo "a"; new foo "b"; new foo "c" ];; > > > > List.iter (fun e -> print_endline (e#to_string ())) l;; > > > > File "test.ml", line 8, characters 52-53: > > This expression has type foo list but is here used with type > > < to_string : unit -> string > list > > Type foo = < to_string : ?opt:string -> unit -> string > > > is not compatible with type < to_string : unit -> string > > > ------------------------------------------------------------ > > This is quite normal: since the type of e is not constrained, ocaml > has inferred the most general one from the body of the function: e > must be an object with a method 'to_string' of type unit -> string > . The problem comes from the fact that optional arguments and type > inference do not work very well together (cf > http://pauillac.inria.fr/ocaml/htmlman/manual006.html section > 4.1.2). > As suggested in the manual, the best solution might be to add a > type annotation in the function above: > > List.iter (fun (e:foo) -> print_endline (e#to_string ())) l;; > or > List.iter (fun (e:#foo) -> print_endline (e#to_string ())) l;; > if you intend to use subclasses of foo Alternatively, one can use an "unwrapped" argument : # List.iter (fun e -> print_endline (e#to_string ?opt:None ())) l;; a b c - : unit = () -- Olivier ------------------- To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/ Beginner's list: http://groups.yahoo.com/group/ocaml_beginners