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

是否有类似的方法从C程序迭代(带有yield)?

有帮助吗?

解决方案

以下是自我答案的社区维基副本,可以选择“该”答案。回答。请将上/下投票指向实际的自我回答

以下是我找到的方法:

    /* 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

中读得更好

其他提示

我不时将这个网址作为一个笑话: Coroutines在C

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

没有

好又短!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top