开发者

What should happen when a generator function is assigned? [closed]

开发者 https://www.devze.com 2022-12-09 03:27 出处:网络
Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing
Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 7 years ago.

Improve this question

If I have a programming language with first class functions. What should the semantics be when a generator function is shared?

For example:

开发者_开发知识库
var f = function() { 
  foreach (i in 0..42)
     yield i;
}

int a = f(); // 0
int b = f(); // 1

// Assigning the generator function 
var g = f;

int c = g(); // ??
int d = f(); // ??

I can imagine three things:

  1. c == 2, d == 3 meaning that the generator function is shared
  2. c == 0, d == 2 meaning that a new generator function is created, with the values initialized
  3. c == 2, d == 2 meaning that a new generator function is created by copying the current state of the generator

The best answer in my opinion, would provide the most compelling argument to do one mechanism or another. Often I find that prior art is the most persuasive argument.


If you have reference semantics in your language, and assignment is usually reference assignment, then you want option 1.

This is what happens in Python, where generates are objects, and assignment is reference assignment (even though you invoke .next() to retrieve the next value, rather than "calling" the generator).

Here is a brief demonstration how this behaves in Python:

>>> def gen():
...   for i in range(42):
...     yield i
... 
>>> f = gen().next
>>> a = f()
>>> b = f()
>>> g = f
>>> c = g()
>>> d = f()
>>> a, b, c, d
(0, 1, 2, 3)
0

精彩评论

暂无评论...
验证码 换一张
取 消