简体   繁体   中英

Managing dynamic dependencies in OCaml

Imagine a library in OCaml which might need to store its data somewhere. This persistence layer can be implemented with different libraries (sqlite, MySQL, PostgreSQL and so on). And depending on the concrete technology of the storage, it may offer different features and performance guarantees.

What are possible ways to manage external dependencies for such library? Let's say if I develop with MySQL I do not want to introduce neither compile time nor runtime dependencies on sqlite.

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

You would probably define a module type to abstract over all the implementations. eg

module type DB =
  sig
    type t
    type results

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

Then you would write your code to take an implementation of this module type 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'd need a separate main function to connect to some actual database, which might be DB-specific, but the rest of the code just uses the abstract DB .

(Of course, you'd use a better API than this string-based one. This is just a simple example.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM