Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access a type defined in one .ml file in another .ml file

Tags:

ocaml

In a.ml a record type t is defined and is also defined transparently in a.mli, i.e. in d interface so that the type definition is available to all other files.

a.ml also has a function, func, which returns a list of t.

Now in another file, b.ml i m calling func, now obviously ocaml compiler wud nt be able to infer d type of objects stored in d list, for compiler its just a list. so in b.ml, i hav something like dis,

let tlist = A.func in
let vart = List.hd tlist in
printf "%s\n" vart.name     (*name is a field in record t*)

Now here i get a compiler error sayin "Unbound record field label name" which makes sense as compiler can't infer d type of vart.

my first question: how do I explicitly provide d type of vart as t here? i tried doing "let vart:A.t = " but got the same error.

I also tried creating another function to fetch the first element of d list and mentioning return type as A.t, but then i got the "Unbound value A.t". I did this:

let firstt = function
     [] -> 0
   | x :: _ -> A.t x ;;

The problem is compiler is unable to recognize A.t (a type) in b.ml but is able to recognize function A.func. If I remove A.t from the b.ml, i don'get any compiler errors.

like image 337
focus Avatar asked May 12 '10 12:05

focus


1 Answers

The compiler is able to recognize A.t to designate type t from file a.ml.

On the other hand, t x where t is a type and x a variable is not a valid expression. This is the source of your problem. The compiler looks for the name t in the variables exported by a.ml. Since it cannot find this name used for a variable, it reports an error.

Now for what you were trying to do:

  • type annotations are not hints to the compiler in OCaml. It has an algorithm to infer the (most general, with some exceptions I am not entering into) type and then it checks that your annotation is at least a particularization of the most general type. The type annotation you provide will never (again, with some possible exceptions that do not concern you) make it change its mind.

  • To access in file b.ml the field f of a record r of type A.t, type r.A.f.

like image 54
Pascal Cuoq Avatar answered Oct 16 '22 18:10

Pascal Cuoq