Ilya Zakharevich on Thu, 18 Jan 2024 04:54:38 +0100


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: Is it possible to implement closures in PARI?


On Sun, Jan 14, 2024 at 01:05:41PM +0100, Bill Allombert wrote:
> > Currently, PARI supports anonymous subroutines memoizing values of
> > lexical variables (at the moment of creation).  Is it theoretically
> > possible to implement¹⁾ closures instead? — In other words: are
> > closures compatible with the PARI⸣s memory model?
> 
> Probably not. The problem is well-documented:
> <https://en.wikipedia.org/wiki/Funarg_problem>
> 
> The problem is that the variable scope might end before the closure scope,
> so the closure would have a reference to a freed variable, so we would need
> smarter memory management than the stack.

Sorry, but this situation is quite delicate, so it makes very little
sense to discuss matters unless one switches to a pedantic
mode. — Which I do now.

  In this mode, a variable scope CANNOT END before the closure’s
  scope.  By definition of closure!

And: in this pedantic mode, one must distinguish scopes of the
variable’s name resolution, and the scope of the variable’s
“identity”.  When a variable can no longer be resolved by name¹⁾, the
“scope of its identity” (or: “reachability of its content”) does not end.

  ¹⁾ Here I ignore the yet-more-delicate question of “how should
     eval() resolve names”!

This scope ends only when a variable’s content cannot be reached via a
chain of closures-mentioning-other-closures-etc.-…-mentioning␣this␣variable.

⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜

So I see now: as far as the things come-and-go to/from stack without
any warning, one cannot trace when the “scope of the variable’s
identity ends” — if it ever was mentioned from a closure.

⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜⁜

> Also it would not be compatible with parallelism, which require closures to
> be immutable.

In what sense a closure-in-the-sense-of-CS is “mutable”?

Thanks,
Ilya