exploring-reasonml
exploring-reasonml copied to clipboard
Chapter: `let` bindings and scopes
How to redefine variables in the outer scope. For example:
let n = 1;
let inc = () => { let n = n + 1; print_int(n) };
The inc
function is trying to increase the variable n
when invoked, but what it actually does is define a new variable n
in the nested scope I think. Is it possible to redefine variables in the outer scope?
@theJian : To modify n you need
- to make "n" a "ref cell" and
- remove in the body of inc-function the additional let-binding (which is shadowing the "n" of the toplevel).
In standard OCaml-Syntax:
# let n = ref 0;;
val n : int ref = {contents = 0}
# let inc () = n := !n+1; print_int !n;;
val inc : unit -> unit = <fun>
# inc ();;
- : unit = <unknown constructor>
# !n;;
- : int = 1
https://realworldocaml.org/v1/en/html/imperative-programming-1.html#ref-cells