1
0
mirror of https://github.com/exaloop/codon.git synced 2025-06-03 15:03:52 +08:00
codon/docs/language/generators.md
A. R. Shajii d5ce1f8ff9
Update docs (#28)
* Update docs

* Update docs

* Update docs

* GitBook: [#4] Add hint

* Update primer

* Re-organize docs

* Fix table

* Fix link

* GitBook: [#5] No subject

* GitBook: [#6] No subject

* Cleanup and doc fix

* Add IR docs

* Add ir docs

* Fix spelling error

* More IR docs

* Update README.md

* Update README.md

* Fix warning

* Update intro

* Update README.md

* Update docs

* Fix table

* Don't build docs

* Update docs

* Add Jupyter docs

* FIx snippet

* Update README.md

* Fix images

* Fix code block

* Update docs, update cmake

* Break up tutorial

* Update pipeline.svg

* Update docs for new version

* Add differences with Python docs
2022-07-26 16:08:42 -04:00

1022 B

Codon supports generators, and in fact they are heavily optimized in the compiler so as to typically eliminate any overhead:

def gen(i):
    while i < 10:
        yield i ** 2
        i += 1

print(list(gen(10)))  # prints [0, 1, 4, ..., 81]
print(list(gen(0)))   # prints []

You can also use yield to implement coroutines: yield suspends the function, while (yield) (i.e. with parenthesis) receives a value, as in Python.

def mysum(start):
    m = start
    while True:
        a = (yield)     # receives the input of coroutine.send() call
        if a == -1:
            break       # exits the coroutine
        m += a
    yield m

iadder = mysum(0)       # assign a coroutine
next(iadder)            # activate it
for i in range(10):
    iadder.send(i)      # send a value to coroutine
print(iadder.send(-1))  # prints 45

Generator expressions are also supported:

squares = (i ** 2 for i in range(10))
for i,s in enumerate(squares):
    print(i, 'x', i, '=', s)