How would something like let y = "string" in let local_ z = y in y work? Doesn't this kinda escape its region - but y is global so it should be fine but it's not in terms of z being local also being equal to y? What about if it's not just a string but a ref?
@RichardEisenberg-JS Жыл бұрын
Global/local is something that applies to expressions and values, not memory locations. So in your example, z is local (and would not be allowed to escape) and y is global. So returning y is just fine -- even if y and z are aliased in memory. The same is true for a mutable reference: a local variable can be aliased with a global, and the global one is allowed to escape.
@huge_letters Жыл бұрын
@@RichardEisenberg-JS I see I was just thinking in terms of your previous example with a file handle. Say, a function creates and returns a file handle - wouldn't it be able to retain it through those means? Or it then just guarantees that the ref is local, not the underlying value? Anyways I'm glad to be learning OCaml during such resurgence :)
@RichardEisenberg-JS Жыл бұрын
@@huge_letters There's a subtlety in the way that question is phrased, mentioning returning the file handle. If a function returns a file handle, then the handle can't be local -- there's no way to control where it will end up (as you rightly surmise). But we can still protect file handles by using a callback (or continuation, if you prefer that term): `with_file : string -> (local_ handle -> 'r) -> 'r`. Once something is local, it can't be made global, so that file handle will be protected.