English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
[Caml-list] Module/functor question
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2004-03-14 (18:52)
From: ronniec95@l...
Subject: [Caml-list] Module/functor question

I'm trying to acheive the following effect in Ocaml that I should be
able to do but am getting very confused with modules and functors...

I have a set of classes all with the structure:-

class Foo {
	Foo* create(std::string x);
	std::string toXml(Foo*);
	... /* Other methods */

	int m_x;
	std::string m_y;
and I have a template function

template<typename T>
void serialisetoxml(T* x) { printf("%s\n",x->toXml().c_str());}

int main()
	Foo* f = new Foo(1,"hello");

The effect I want to acheive is to have a function that takes any module
that has a toXml function defined and invokes it somewhere.

The closest I got was

type t (* this doesn't work...*)
module type Serialise
	val create : Xml.xml -> t (*Using XML-Light here *)
	val to_xml : t -> Xml.xml

type t = { x : int ; y:int }
module Make
	val create : Xml.xml -> t (*Using XML-Light here *)
	val to_xml : t -> Xml.xml

type t = { x : int ; y:int }
module Make : Serialiser =
	let create (f: Xml.xml) = Xml.Element("Foo",[("x",string_of_int f.x);("y",f.y))])
	let to_xml (foo : t) = ...
	(* It thinks f is of type Serialiser.t and not Foo.t *)

(* main.ml *)
module Sender (C : Serialiser) =
		let serialisetoxml msg = print_string (Xml.to_string (C.as_xml msg))

(* was hoping for something like this *)
let _ = let m = module Sender(Foo.Make) in
	m.serialisetoxml (Foo.Make (Xml.parse_from "..."));

but I cannot figure out how to declare Foo having a signature of
Serialiser and then use it in main somehow. Assume also that I have
lots of other modules which have same basic interface but additional
methods specific to the modules.

Any help appreciated.




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