Feature #9037

Memoization of "anonymous constants"

Added by Tsuyoshi Sawada 6 months ago.

[ruby-core:57945]
Status:Open
Priority:Normal
Assignee:-
Category:-
Target version:-

Description

=begin
I was thinking about the frozen literal argument in https://bugs.ruby-lang.org/issues/8992. I believe that the original intent for that proposal was to avoid reevaluation of specially marked string literals. I think that that idea would be best realized by memoization of a literal rather than freezing. Suppose we introduce a method memoize like this:

memoize{"foo"}

whose block would be evaluated only the first this expression it is parsed, and always returns the return value of the block, then that would suffice for the purpose. In fact, this proposal in an extension/generalization of the arguments regarding frozen array/hash literals. The proposed syntax allows objects of an arbitrary class to be memoized, and is regardless of whether it is a literal expression. It is also independent of and is free from the difficulties regarding what to do with frozen arrays/hashes.

At the Ruby level, I believe there is a way to implement this by keeping a hash whose key would be something that uniquely identifies the source location of this expression. But I also believe there must be a better way at the C level.

If it is possible to add a keyword to the syntax, then we can have memoize as a keyword (of the kind similar to defined?) instead of a method, used like:

memoize("foo")

or

memoize "foo"

which might look more pleasant.

In either case, for Ruby 2.0 compatibility, a method memoize can be defined to evaluate the block or return the argument.

=end


Related issues

Related to ruby-trunk - Feature #8804: ONCE syntax Open 08/20/2013

Also available in: Atom PDF