제너레이터

1 개요[ | ]

generator
제너레이터
  • 반복문의 반복행동을 제어할 수 있는 특수 루틴
  • 모든 제너레이터는 이터레이터

2 PHP 예시[ | ]

function fibonacci() {
    $last = 0;
    $current = 1;
    yield 1;
    while (true) {
        $current = $last + $current;
        $last = $current - $last;
        yield $current;
    }
}
 
foreach (fibonacci() as $number) {
    echo $number, "\n";
}

3 Python 예시[ | ]

def countfrom(n):
    while True:
        yield n
        n += 1

for i in countfrom(10):
    if i <= 20:
        print i
    else:
        break

def primes():
    n = 2
    p = []
    while True:
        if not any( n % f == 0 for f in p ):
            yield n
            p.append( n )
        n += 1
 
>>> f = primes()
>>> f.next()
2
>>> f.next()
3
>>> f.next()
5
>>> f.next()
7

4 같이 보기[ | ]

5 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}