Mutable record field is not mutable?

Following code prints 3 and i expected 4,

type anint = {mutable i:int}
let a:anint={i=3};;
let increment (x:anint)=
    x.i=x.i + 1 ;;
increment a;;
print_int a.i;;

I made a small modification, now it works

type anint = {mutable i:int}
let ()=
    let a:anint={i=3} in 
    let increment (x:anint)=
        x.i <- x.i + 1 ;
        () in
    increment a ;
    (* prints 4*)
    print_int a.i;;

Unrelatedly, a few suggestions to simplify your code, by removing type annotations that can be inferred and an unnecessary ():

type anint = { mutable i : int }
let () =
    let a = {i=3} in 
    let increment x = x.i <- x.i + 1 in
    increment a ;
    (* prints 4*)
    print_int a.i
1 Like

The clue to the problem was in the type given to your functions, in particular increment, which has type anint -> bool instead of the anint -> unit. OCaml assists a little more with a warning if you’d structured it:

type anint = {mutable i:int}
let a:anint={i=3}
let increment (x:anint)=
    x.i=x.i + 1
let () =
  increment a;
  print_int a.i;;

as you get Warning 10 “this expression should have type unit.” from the increment a line.