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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With