gpt4 book ai didi

C 中的 Python 风格迭代器

转载 作者:太空狗 更新时间:2023-10-29 22:24:08 27 4
gpt4 key购买 nike

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

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

最佳答案

下面是 self 回答的社区维基副本,可以将其选为“the”答案。请直接对实际的 self 回答投赞成票/反对票

这是我找到的方法:

    /* 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 中读起来更好

关于C 中的 Python 风格迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/833063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com