I would be fine with staticmethods if there is no other solution than using objects.
Generator syntax
Introduce an decorator to mark accessible fields. Otherwise code for every variable would have to be
generated which could lead to unnecessarily large structs and less optimized code.
The coroutine_name
decorator can be used to explicitly name the coroutine.
extension[T: Copyable & Movable] List[T](Iterable):
alias Element = T
@coroutine_name("ListIterGenerator")
fn __iter__(ref self) yields Self.Element:
# can't be optimized out
@coroutine_state
count = 0
while count < len(self):
yield self[i]
count += 1
struct ListIterGenerator[T](Iterator): # fields generated by the compiler
var _list_: UnsafePointer[List[T]]
var _goto_state_: UniqueGotoState
var _count: Int
fn _get_count(ref self) -> Int:
# internal logic
# iterated so far extension
fn iterated_so_far(ref self) -> Int
return self._get_count()
You know, lambdas are limited to 1 expression, which makes it likely that your example will have to refactored at some point.
I don’t think using 4 iterator adapters is more readable than any of the alternatives.
def return_generator():
for x in X:
if cond_x(x):
for y in Y_fn(x):
if cond_y(x, y):
yield expr(x, y)
def iterate_in_place():
for x in X:
if cond_x(x):
for y in Y_fn(x):
if cond_y(x, y):
use_in_plnace(x, y)
Also your example does not show why iterators need to be methods:
return X.iter()
.filter(lamda x: cond_x(x))
.map(lambda x: (x, Y_fn(x)))
.filter(lambda (_x, y): cond_y(y) )
.map(lambda (x, y): expr(x, y) )
# can be expressed as:
unnamed_tempory1 = filter(lamda x: cond_x(x), X)
unnamed_tempory2 = map(lambda x: (x, Y_fn(x)), unnamed_tempory2)
unnamed_tempory3 = filter(lambda (_x, y): cond_y(y), unnamed_tempory3)
unnamed_tempory4 = map(lambda (x, y): expr(x, y), unnamed_tempory4)
return unnamed_temporary4
I like take
, zip
and group_by
. Generator expression return an iterator, which means they can be combined.
I don’t think this is a good idea, since not all iterables are suitable for iterating. With functions there are also no downside to using Iterable.