JuliaDynamics / ResumableFunctions.jl

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

resumable should have SizeUnknown() so collect and comprehensions work #5

Closed ggggggggg closed 6 years ago

ggggggggg commented 6 years ago

See docs for iteratorsize. Consider the following, which prints "second worked" for me.

using ResumableFunctions

@resumable function fibonnaci(n::Int) :: Int
  a = 0
  b = 1
  for i in 1:n-1
    @yield a
    a, b = b, a+b
  end
  a
end

a = fibonnaci(10)

c=try 
  b = fibonnaci(10)
  c=collect(b)
  println("first worked")
  c
catch
  Base.iteratorsize(::Type{typeof(a)}) = Base.SizeUnknown()
  b = fibonnaci(10)
  c=collect(b)
  println("second worked")
  c
end   

@show c

SizeUnknown() would be a strict improvement, but it seems like it would be possible to define length and size correctly for some iterators, such as the fibonnaci example, but it would require extra syntax.

ggggggggg commented 6 years ago
using ResumableFunctions

@resumable function fibonnaci(n::Int) :: Int
  a = 0
  b = 1
  for i in 1:n-1
    @yield a
    a, b = b, a+b
  end
  a
end
Base.iteratorsize(::Type{T}) where T<:ResumableFunctions.FiniteStateMachineIterator = Base.SizeUnknown()
a = fibonnaci(10)
collect(a)

is a better way to do this.