[
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: | 2002-08-23 (17:32) |
From: | Fred Smith <fsmith@m...> |
Subject: | RE: [Caml-list] Polymorphic methods |
Hi, The method set_t would not be type safe given the type you have assigned it. OK, the code snippet you wrote happens to be safe but won't be as soon as you try to use it. With the type you have assigned set_t the following would be legal: n#set_t 3.4; n#set_t "hello"; because set_t takes any type as input ('a.'a->unit). What type would n#t have? Neither float option nor string option will work. In particular, if you had provided a function get_t it could not return a useful single type. To see the problem consider if myWhackoCondition then (n#set_t 3.4) else (n#set_t "hello"); let w = n#get_t () in (* What type should w have? *) A class definition that is legal and may solve your problem is: class ['a] node = object val mutable t : 'a option = None method set_t nt = t<- Some nt method get_t () = (match t with Some x -> x | _ -> failwith "Empty node") method is_empty () = (t = None) end Now you can create values of type int node, float node, etc... and set_t and get_t will return the appropriate types. But you cannot create a value of type 'a.'a node for the same reasons as above. Hope this helps. -Fred > -----Original Message----- > From: owner-caml-list@pauillac.inria.fr > [mailto:owner-caml-list@pauillac.inria.fr]On Behalf Of Frederic Tronel > Sent: Friday, August 23, 2002 11:46 AM > To: caml-list@inria.fr > Subject: [Caml-list] Polymorphic methods > > > Hello list, > > > I've just compiled the new 3.05 version (I will change for 3.06 > tomorrow), > and start playing a little bit with polymorphic methods. > But this small piece of code does not compile: > > class node = > object > val mutable t = None > method set_t: 'a. 'a -> unit = fun nt -> t <- Some nt > end > > File "essai.ml", line 4, characters 31-53: > This method has type 'a -> unit which is less general than 'b. 'b -> > unit > > while this one is OK (useless). > > class node = > object > val mutable t = None > method set_t: 'a. 'a -> unit = fun nt -> () > end > class node : object val mutable t : 'a option method set_t : 'b -> unit > end > > Where am I going wrong ?? > > Best regards, > > Frederic. > ------------------- > 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 > ------------------- 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