Browse thread
polymorphic lists, existential types and asorted other hattery
[
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: | Julien Moutinho <julien.moutinho@g...> |
| Subject: | Re: [Caml-list] polymorphic lists, existential types and asorted other hattery |
On Tue, Nov 13, 2007 at 12:27:07PM -0500, Peng Zang wrote:
> Is there a way to create lists in which the elements may be of
> differing types but which all have some set of operations defined
> (eg. tostr) in common?
> [...]
Objects may be of interest to you:
% cat file.ml
class ['e] skel (e: 'e) =
object
val mutable e = e
method get = e
method set x = e <- x
end
class virtual ['e] xs
(to_string: 'e -> string) =
object (self)
method virtual get : 'e
method coerce = (self :> < show : string >)
method show = to_string self#get
end
class oint (e: 'e) =
object
inherit ['e] skel e
inherit ['e] xs string_of_int
end
class ofloat (e: 'e) =
object
inherit ['e] skel e
inherit ['e] xs string_of_float
end
let xs =
[ (new oint 1)#coerce
; (new ofloat 2.0)#coerce
; (new oint 3 :> < show : string >)
; (object method show = "soleil" end)
]
;;
List.iter (fun o -> print_endline o#show) xs
% ocaml file.ml
1
2.
3
soleil
% ocamlc -i file.ml
class ['a] skel :
'a -> object val mutable e : 'a method get : 'a method set : 'a -> unit end
class virtual ['a] xs :
('a -> string) ->
object
method coerce : < show : string >
method virtual get : 'a
method show : string
end
class oint :
int ->
object
val mutable e : int
method coerce : < show : string >
method get : int
method set : int -> unit
method show : string
end
class ofloat :
float ->
object
val mutable e : float
method coerce : < show : string >
method get : float
method set : float -> unit
method show : string
end
val xs : < show : string > list
HTH,
Julien.