OCaml record accessing itself

321 views Asked by At

I'm reading OCaml code where lots of records are defined. These records define functions for an interactive command line tool.

The type of these records is:

{
  name : string ;
  help : string ;
  run : string list -> unit
}

where name is the name of the command, help one little line of help for the function, and run a function that takes arguments and computes the result.

I would like to use the name field inside the run function. Is there a way to do that? Something like a self.name?

The tool must support OCaml>4.00.1.

Thanks

1

There are 1 answers

2
Martin Jambon On BEST ANSWER

Yes, you can define a record recursively with the rec keyword, roughly speaking as long as all the fields are guaranteed to not involve an arbitrary computation. The following works:

type t = {
  name : string;
  help : string ;
  run : string list -> unit
}

let run x l =
  print_endline x.name

let rec x = {
  name = "a";
  help = "b";
  run = (fun l -> run x l);
}

However, this doesn't work:

let rec x = {
  name = "a";
  help = "b";
  run = (run x);
}