mirror of
https://github.com/exaloop/codon.git
synced 2025-06-03 15:03:52 +08:00
* Fix #75 * Build on macOS 11 for #72 * Fix #76 * Fix test * Fix generator example in docs * Fix Python/Cython packaging; Fix #80 * Fix tests * Fix tests * Fix tests * Fix tests * Fix syntax * Fix CI * Fix CI * Fix CI; Dominate imported bindings * Fix CI; Dominate imported bindings * Fix .gitignore * Fix tests * Fix rm command * Format * clang-format * Organize and optimize string formatting * Fix format error message Co-authored-by: Ibrahim Numanagić <ibrahimpasa@gmail.com>
1.0 KiB
1.0 KiB
Codon supports generators, and in fact they are heavily optimized in the compiler so as to typically eliminate any overhead:
def gen(n):
i = 0
while i < n:
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)