JuliaDynamics / ResumableFunctions.jl

C# style generators a.k.a. semi-coroutines for Julia.
Other
160 stars 19 forks source link

Length of iterators #41

Closed baggepinnen closed 2 months ago

baggepinnen commented 4 years ago

It would be convenient if was possible to supply the length of a resumable function if the length is known. A lot of functions around the ecosystem do not work if they can't ask for the length. E.g.,

@resumable n myfun(n)
    for i = 1:n
        @yield i
    end
end
BenLauwens commented 4 years ago

Hi

This could be implemented by having a @resumable macro with two inputs. I will put it on my todo list;)

Kind regards

Ben

SyxP commented 4 years ago

The length of the iterators may be highly non-trivial to compute at times. I propose the following syntax with the second shorthand. This is slightly longer, but I think covers a wider range of cases. (Ill try to look at the internals and see if I can implement it)

@length myfun(n)
     # computation of length
     return length
end

@length myfun2(n) = n

So in the case of baggepinnen, we would write instead

@resumable myfun(n)
    for i in 1:n
        @yield i
    end
end
@length myfun(n) = n