Equivalent OCaml Types

I am creating two libraries in OCaml that contain the same option. The detail of the variant is not very important, except that it is really large, and it would be unpleasant to manually write conversion functions for it. (This is actually a bfd_architecture enum converted from C using ocamlidl).

Now I am writing a program using two libraries. In particular, I call Af, which returns the value A.variant_type, and I need to use this value in a call to Bg, which takes the value B.variant_type as input.

Is it possible to tell OCaml that A.variant_type and B.variant_type are really the same type, and thus it is possible to convert a value from one to another? Libraries are independent, therefore they should not refer to each other. Right now I'm using Obj.magic to convert, but this is a hack.

+6
source share
3 answers

You do not need to use Obj.magic , although you need to use some β€œmagic”,

 external convertAB : At -> Bt = "%identity" external convertBA : Bt -> At = "%identity" 

enough to convert. Of course, I understand your concern; both types should be exactly the same as you will deal with runtime errors. If this is possible and appropriate, converting these options to Polymorphic options will solve the problem.

+1
source

I believe that there is no clean way if there is no common dependency in these libraries that defines this type (i.e. the same module that both libraries reference during assembly).

+8
source

If you really want the variant type to appear in both libraries, you can also force check that they are equivalent. In the second library you can write:

 type t = OtherLib.t = | A | B | C | ... 

This will cause the compiler to verify that OtherLib.t = A | B | C | ... and make two types equal. I do not think this really solves your case, since you probably do not want to change any of the libraries.

I usually do this when I want to save different versions of the type (because they are saved in files that I want to read later), and I want each version to explicitly create constructors, while preserving the equivalence, when possible, with the current version .

+3
source

Source: https://habr.com/ru/post/908517/


All Articles