views:

80

answers:

1

Hello, I'm developing some algorithms in OCaml which need some parts to be "pluggable" so that part of the computation is left to specific computators.

Just to make an example suppose I have a signature like this one:

module type Algorithm = sig
    val feed : float -> unit
    val nth : int -> (float -> float)
end

And two different implementations that will be Alg1 and Alg2. This Algorithm module should represent the interface for various implementations like these two one.

Now I need another component, let's call it Executor that will be the module that uses Alg1 or Alg2 throught their interface..

Reading about functors it seems that I should need a functor that takes an Algorithm and produces a ConcreteExecutor with a specific implementation of the algorithm I need. So that Executor is a sort of module that is parametrized over one of its components..

Am I right? Is it the best way to obtain what I need? I'm wondering thinkgs like these because I come from a Java/C++ background so I'm used to use interfaces and abstract classes and I need to get into this functor/module abstraction issue in the correct way.

Which is the correct syntax to obtain what I want?

Thanks in advance

+3  A: 

Yup, it sounds like functors are what you want. In fact, you can take a look at how the standard library uses functors as the source code is available. On my machine it's located at /usr/lib/ocaml/3.10.2/. As an example, set.mli contains the following:

module type OrderedType =
  sig
    type t
    val compare : t -> t -> int
  end

module type S
  sig
    ...
  end

module Make (Ord : OrderedType) : S with type elt = Ord.t

When you want to use a set in OCaml you do:

module SSet = Set.Make(String);;

So with your code, Algorithm replaces OrderedType, Alg1/Alg2 replaces String, Executor replaces Make, and ConcreteExecutor is the result of Executor(Alg1/Alg2). You'll also notice that string.mli/ml doesn't contain any mention of OrderedType. String is an OrderedType by virtue of it having a type t that is used by a function compare. You don't need to explicitly say that String is an OrderedType.

Niki Yoshiuchi
You need to update ocaml. :)
nlucaroni
Ha! That's the version on a machine I don't have root access to. My home machine is more up-to-date (although who knows when Debian will get 3.12?).
Niki Yoshiuchi
@Niki It may take some time, but you know that lack of compatibility between OCaml versions is to blame for the delays, right? The Debian "OCaml maintainers" have to make sure that all OCaml packages in Debian compile with the new version, and switch them all at once. They are doing a great job and this is not their fault.
Pascal Cuoq
@Pascal Actually I didn't there were compatibility issues. Either way I realize that maintaining Debian packages is hard work and I didn't mean to imply otherwise.
Niki Yoshiuchi