exploring-reasonml icon indicating copy to clipboard operation
exploring-reasonml copied to clipboard

Chapter: `let` bindings and scopes

Open rauschma opened this issue 6 years ago • 2 comments

rauschma avatar Feb 07 '18 06:02 rauschma

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 avatar Mar 02 '18 08:03 theJian

@theJian : To modify n you need

  1. to make "n" a "ref cell" and
  2. 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

salamynder avatar Mar 29 '18 16:03 salamynder