For what it’s worth, I haven’t seen anyone else suggest what I normally do, which is set up all my definitions, then set up a main
function for things which have side effects, then call the main
function:
let a = ref 0
let b = ref 0
let f x = x + !a
let g x = x + !b
let c x = f x + g x
let main () =
a := 1;
b := 1;
Printf.printf "%d\n" (c 10);
a := 2;
b := 2;
Printf.printf "%d\n" (c 10)
let () = main ()
With a little practice, it’s fairly easy to tell what has side effects–usually any expression that returns unit
e.g. a := 1
. These can be combined together with ;
.
Finally, you run the main
function at the bottom to actually carry out all the side effects.