On 9 September 2014 16:32, Yotam Barnoy <yotambarnoy@gmail.com> wrote:
> I have a question about the implicit module implementation: Is there any way to
> combine modules automatically? For example, suppose I have a Show implicit
> module and an Ord implicit module, and a function receives both, and wants
> to infer both functionalities for an incoming type so we can run both show
> and compare on the same type. Does the current model cover such a use-case?
Yes, it does. The implicits language is essentially the same as
OCaml's module language, so you can use constraints/equations on the
module types in the regular way. For example, suppose you have module
types for SHOW and ORD together with corresponding top-level
functions:
module type SHOW =
sig
type t
val show : t -> string
end
let show (implicit Show : SHOW) (x : Show.t) = Show.show x
module type ORD =
sig
type t
val compare : t -> t -> int
end
let compare (implicit Ord : ORD) (x : Ord.t) (y : Ord.t) = Ord.compare x y
You can write a function which operates on a value with implicit
instances for both SHOW and ORD by adding some kind of type
constraint. For example, you might write:
let f (implicit Show: SHOW) (implicit Ord: ORD with type t =
Show.t) (x : Show.t) y =
if compare x y < 0 then show x else show y
or perhaps
let f (type a) (implicit Show: SHOW with type t = a) (implicit Ord:
ORD with type t = a) (x : a) y =
if compare x y < 0 then show x else show y
The inferred type is just as you'd expect:
val f :
(implicit Show : SHOW with type t = 'a) ->
(implicit Ord : ORD with type t = 'a) ->
'a -> 'a -> string
You might like to try out the implementation for yourself, either via
the opam switch or via the IOCaml top-level that Andrew Ray's set up:
http://andrewray.github.io/iocamljs/modimp_show.html