Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

reference - value not updated when incrementing mutable ref

Below is an extract of code : (the problem is visible by testing only this extract)

let cptIdCO = ref 0;; (* compteur : id Classe et Object globale *) 

let makeEtiClassOrObj =
  cptIdCO := !cptIdCO + 1;
  "ClObj_" ^ (string_of_int !cptIdCO) ^ ": NOP
";;

let compileClass cls =
  print_string "-- compileClass
";
  (*fillClass cls;*)
  print_string makeEtiClassOrObj;
  
and compileObject obj =
  print_string "-- compileObject 
";
  print_string makeEtiClassOrObj;

When calling compileClass or compileObject several times, the output is always ClObj_1: NOP so it seems that the reference is not updated and I don't understand why.

I saw some uses of ^:= and !^ but it don't work and I don't understand the difference between the normal and ^ versions.

question from:https://stackoverflow.com/questions/65870593/value-not-updated-when-incrementing-mutable-ref

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is not the way you update the reference, but that makeEtiClass is not a function, just a variable holding a string, that happens to increment cptIdCO once before initializing it.

A function differs from a variable in that it takes arguments. You can use unit, (), if it doesn't need anything else.

This will do what you expect:

let cptIdCO = ref 0;; (* compteur : id Classe et Object globale *) 

let makeEtiClassOrObj () =
  cptIdCO := !cptIdCO + 1;
  "ClObj_" ^ (string_of_int !cptIdCO) ^ ": NOP
";;

let compileClass cls =
  print_string "-- compileClass
";
  (*fillClass cls;*)
  print_string (makeEtiClassOrObj ())
  
and compileObject obj =
  print_string "-- compileObject 
";
  print_string (makeEtiClassOrObj ())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...