【问题标题】:Python style iterators in CC中的Python风格迭代器
【发布时间】:2009-05-07 05:52:46
【问题描述】:

python 中的“yield”语句允许从过程中进行简单的迭代,这也意味着不需要预先计算序列并将其存储在“任意”大小的数组中。

是否有类似的方式从 C 过程中迭代(使用 yield)?

【问题讨论】:

  • 问这个问题有什么意义?您只是想自己回答以提高评分吗?昨天在 Reddit 上,所以我认为这不是巧合。所以你的问题得到-1,我的答案得到-1。
  • 你应该只在 SO 提问。我很欣赏你分享知识的意图,但像 Reddit 和 Digg 这样的地方更适合这个。我会撤消我的反对意见,因为您的错误是无意的。
  • @qrdl 这是很久以前处理的 (stackoverflow.com/questions/2572) NevilleDNZ 的行为不仅可以接受,而且值得鼓励。您甚至可以在回答您自己的问题时获得 3 票赞成的徽章。这是一个提问和回答的地方,一个人提供两者的事实不容小觑。
  • 每当我发现此类案例时,我都会将自我答案复制粘贴到社区维基拥有的答案,该答案可以选择为“该”答案(因为问题已得到回答) .

标签: python c iterator jit algol68


【解决方案1】:

下面是自我答案的社区 wiki 副本,可以选择作为“该”答案。请直接对实际的自我回答投赞成票/反对票

这是我找到的方法:

    /* Example calculates the sum of the prime factors of the first 32 Fibonacci numbers */
#include <stdio.h>

typedef enum{false=0, true=1}bool;

/* the following line is the only time I have ever required "auto" */
#define FOR(i,iterator) auto bool lambda(i); yield_init = (void *)&lambda; iterator; bool lambda(i)
#define DO {
#define     YIELD(x) if(!yield(x))return
#define     BREAK return false
#define     CONTINUE return true
#define OD CONTINUE; }
/* Warning: _Most_ FOR(,){ } loops _must_ have a CONTINUE as the last statement. 
 *  *   Otherwise the lambda will return random value from stack, and may terminate early */

typedef void iterator; /* hint at procedure purpose */
static volatile void *yield_init;
#define YIELDS(type) bool (*yield)(type) = yield_init

iterator fibonacci(int n){
   YIELDS(int);
   int i;
   int pair[2] = {0,1};
   YIELD(0); YIELD(1);
   for(i=2; i<n; i++){
      pair[i%2] = pair[0] + pair[1];
      YIELD(pair[i%2]);
   }
}

iterator factors(int n){
  YIELDS(int); 
  int i;
  for(i=2; i*i<=n; i++){
    while(n%i == 0 ){
      YIELD(i);
      n/=i;
    }
  }
  YIELD(n);
}

main(){
    FOR(int i, fibonacci(32)){
        printf("%d:", i);
        int sum = 0;
        FOR(int factor, factors(i)){
            sum += factor;
            printf(" %d",factor);
            CONTINUE;
        }
        printf(" - sum of factors: %d\n", sum);
        CONTINUE;
    }
}

http://rosettacode.org/wiki/Prime_decomposition#ALGOL_68 得到这个想法 - 但它在 C 中读起来更好

【讨论】:

  • 这看起来非常棒,但是有没有关于它是如何工作的解释。我对整个 auto bool lambda 语句感到非常困惑。
  • 好吧,没关系。我觉得我懂了。基本上它将被迭代的实际循环声明为一个函数,然后在迭代器函数中调用该函数。
【解决方案2】:

我不时把这个网址拉出来作为一个玩笑:Coroutines in C

我认为您的问题的正确答案是:没有直接的等价物,并且试图伪造它可能不会那么干净或易于使用。

【讨论】:

    【解决方案3】:

    没有。

    又好又短!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-23
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多