6

Python の「yield」ステートメントにより、プロシージャからの単純な反復が可能になります。また、シーケンスを事前に計算して「任意の」サイズの配列に格納する必要がないことも意味します。

Cプロシージャから(yieldを使用して)反復する同様の方法はありますか?

4

3 に答える 3

6

これは、「the」回答として選択できる自己回答のコミュニティ 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 の方が読みやすいです。

于 2009-05-08T08:48:36.617 に答える
3

私はときどき冗談として次の URL を引き出します: Coroutines in C .

あなたの質問に対する正しい答えはこれだと思います: 直接同等のものはなく、それを偽造しようとする試みはおそらくそれほどクリーンでも使いやすいものでもありません.

于 2009-05-07T05:55:25.417 に答える