C语言中的Python样式迭代器

C语言中的Python样式迭代器,第1张

概述python中的“yield”语句允许从过程进行简单迭代,这也意味着序列不需要预先计算并存储在“任意”大小的数组中. 是否有类似的方法从C过程迭代(带有yield)? 下面是自我回答的社区维基副本,可以选择作为“答案”.请直接向上/向下指示实际的自我回答 这是我找到的方法: /* Example calculates the sum of the prime factors of the firs python中的“yIEld”语句允许从过程进行简单迭代,这也意味着序列不需要预先计算并存储在“任意”大小的数组中.

是否有类似的方法从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_inititerator 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中读得更好

总结

以上是内存溢出为你收集整理的C语言中的Python样式迭代器全部内容,希望文章能够帮你解决C语言中的Python样式迭代器所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1207234.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-04
下一篇2022-06-04

发表评论

登录后才能评论

评论列表(0条)

    保存