Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declarations and global reference variables for several files

My folder contains several files, which are compiled in this order: global.ml, zone.ml, abs.ml, main.ml

global.ml contains some reference variables (e.g. let g1 = ref 0) for all the files.

In zone.ml there is a declaration let f = !g1.

In abs.ml, there is g1 := 5, which will be run by main in the beginning of run-time, I consider it as an initialization of g1 given the real run-time context.

Later main will call Zone.f. Curiously, what I realize is that it takes f = 0 instead of f = 5.

Do you think this behavior is normal? If so, what should I change, to make it take the current value of !g1 into account?

PS: Maybe one solution is to make a function let f v = v in zone.ml then let main call Zone.f !g1. But I have several global reference variables as g1 in global.ml, I hope they could be valid over all the files and functions, and I don't want to get them involved in the signature of a function.

like image 212
SoftTimur Avatar asked Feb 05 '12 05:02

SoftTimur


1 Answers

You are basically concerned with the order of evaluation of the top-level values in your modules. The order in which this happens isn't related to the order that you compile the files, but rather the order that they appear when you link the files.

If you ignore the module boundaries, if you link the files in the order you give, what you have is like this:

let g1 = ref 0
let f = !g1
let () = g1 := 5

It shouldn't be surprising that f has the value 0.

Note that your main is not necessarily the first thing that happens at runtime. Top-level values are evaluated in the order the files appear when you link them. Very commonly, main is the last top-level thing to happen (because its file is usually the last one).

(Also note that having a main at all is just a convention, presumably adopted by former C programmers like me. There's no requirement to have a function named main. OCaml just evaluates the top-level values in order.)

Edit:

It's difficult to say how to restructure your code without knowing more about it. The essence of your problem appears to be that you define f as a top-level immutable value in zone.ml but you want its value to follow g1, which is a mutable value.

The simplest suggestion would be to remove the definition of f from zone.ml and replace it everywhere in the file with !g1.

If you want to retain the name f at the top level in zone.ml, you have to redefine it as something other than an immutable value. A function is the most obvious choice:

let f () = !g1

Then you would replace uses of f in zone.ml by f () instead.

like image 135
Jeffrey Scofield Avatar answered Sep 30 '22 14:09

Jeffrey Scofield