Reference cell is another way to define mutable variable without mutable keyword. When using ref keyword, it creates reference cell that contains that you write after ref keyword.
> let x = ref 0;; val x : int ref = {contents = 0;} > x;; val it : int ref = {contents = 0;} > !x;; val it : int = 0 > x := !x + 1;; val it : unit = () > x;; val it : int ref = {contents = 1;} > !x;; val it : int = 1In sample above, x referres reference cell itself, if we want to refer the content of reference cell, we must use !x, and if we want to modify the content of reference cell, wemust use operator :=
No comments:
Post a Comment