tags:

views:

68

answers:

2

Hi,

I m very new to ocaml and i m facing the problem below,

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.

Please help, its urgent work. Thanks in advance!

~Tarun

+3  A: 

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.

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

Here tlist is a function, I suppose it is of type 'a -> A.t list, but you are applying an List.hd on that function when you write let vart = List.hd tlist.

You should provide the argument for your function to get the list of A.t for example let tlist = A.func (your_argument-s-_here), I guess this is the source of your error, the compiler is able to infer types between modules.

martani_net