Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] [RFC] first class inline iterators: iter it = myiter() to allow perfect forwarding of iterators, with delayed evaluation #9374

Closed
timotheecour opened this issue Oct 14, 2018 · 1 comment

Comments

@timotheecour
Copy link
Member

timotheecour commented Oct 14, 2018

iterator myiter(seed:int):auto=
  for a in 0..<seed:
    yield a

# not allowed, since can currently only be used in a `for` context
# let it = myiter(5)

# proposal:
iter it = myiter(5) # not a concrete type: can't use `var a: type(it)`

doAssert it is iterator int
doAssert type(it).name == "iterator int" # with import typetraits

# we can consume it directly
for i in it(): echo i # prints 0, 1, ..., 4

# or we can build a pipeline:
# we can use lazy functionals (eg `mapLazy`) that take input (inline) iterators and output (inline) iterators
iter it3 = it.mapLazy(a=>a*10)

# we can inspect the intermediate types:
doAssert it3.type == iterator int

iter it4 = it3.filterLazy(a=>a<25)

# finally we consume it4
for i in it4(): echo i # prints 0, 10, 20
# this would produce exactly same code as if we did the fully inlined version (that can't use UFCS)
for i in filterLazy(mapLazy(myiter(5), a*10), a<25): echo i

# we can also consume the iterator via a proc that takes input iter and output concrete type (eg seq[int])
let x = it4.toSeq

This solves a number of problems with iterators, especially inline iterators which currently aren't 1st class citizens.
This would enable to pass them around as iterator T to other procs that accept iterator T (which is currently impossible for inline iterators).
It would make for nicer error messages, easier debugging, easier to write iterator pipelines.
This would be a zero-cost abstraction (compared to fully inlining the code)

fixes these

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant