JuliaDynamics / ResumableFunctions.jl

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

iterator interface semantics #4

Closed gasagna closed 6 years ago

gasagna commented 6 years ago

I am testing the functionality of this repo and I stumbled in a silly usability issue. Not really an issue, but the behaviour could be documented better. Consider this code:

using ResumableFunctions

f(x) = 0.5*x*(x-1)

@resumable function foo(x)
    out = f(x)
    for i = 1:4
        @yield out
        out = f(out)
    end
    out
end

t = foo(0.6)

for el in t
    println(el)
end

for el in t
    println(el)
end

Only five numbers are printed in this code, because the second loop does not print any. Naively, I would have expected to have the same sequence printed twice, but this does not happen because the iterator state is hidden inside the resumable function definition and does not get reinitialised when the relevant start method is called.

This makes the semantics of the iterator interface slightly different than other iterators in Julia (e.g. zip([1, 2, 3], [4, 5, 6])). This is perfectly OK for openjournals/joss-reviews#400 to proceed, but it should be documented, e.g. in the Iterator Interface section of the docs.

BenLauwens commented 6 years ago

I see your point. I will update the docs.

BenLauwens commented 6 years ago

I have modified the start method so that the semantics are the same as the other iterators in Julia. There is a caveat that only the state variable is reinitialised but not the other internal variables. So a @resumable function that alters the values of its arguments will show some unexpected behaviour:

julia> @resumable function fib(a, b)
       for i in 1:4
           @yield a
           a, b = b, a+b
       end
       a
       end

fib (generic function with 1 method)

julia> fib_it = fib(0,1)
##660(0x00, 0, 1, 4603404944, 4603404464:257, 8)

julia> for el in fib_it
       println(el)
       end
0
1
1
2
3

julia> for el in fib_it
       println(el)
       end
3
5
8
13
21

I added a comment to the caveats section.

BenLauwens commented 6 years ago

I just released a new version of ResumableFunctions including this modification. So I will close this issue soon. Comments are always welcome.