New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter: `let` bindings and scopes #7

Open
rauschma opened this Issue Feb 7, 2018 · 2 comments

Comments

Projects
None yet
3 participants
@rauschma
Owner

rauschma commented Feb 7, 2018

No description provided.

@theJian

This comment has been minimized.

theJian commented Mar 2, 2018

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?

@salamynder

This comment has been minimized.

salamynder commented Mar 29, 2018

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment