Managing dynamic dependencies in OCaml

Imagine a library in OCaml that you need to store your data. This level of persistence can be implemented using different libraries (sqlite, MySQL, PostgreSQL, etc.). And depending on the specific storage technology, it can offer different features and performance guarantees.

What are the possible ways to manage external dependencies for such a library? Let's say if I'm developing with MySQL I don't want to introduce any compile time or runtime for sqlite.

In C ++, I can use abstract interfaces and put concrete logic into modules conditionally included in my project (depending on the config switches). I am curious how someone would approach the same task in OCaml.

+3


source to share


1 answer


You would probably define the module type for abstraction across all implementations. eg.

module type DB =
  sig
    type t
    type results

    val execute : t -> string -> results
    ...
  end

      

Then you have to write your code to implement the implementation of this type of module as an argument:



 module MyProg (D : DB) = struct
   let run db =
     let r = D.execute db "SELECT ..." in
     ...
 end

      

For a library, that's all you need. For an executable program, you will need a separate main function to connect to some real database, which may be database specific, but the rest of the code just uses abstract DB

.

(Of course you would use a better API than this string one. This is a simple example.)

+5


source







All Articles