juliayield

How to write a simple function in Julia similar to a function with yield keyword in python


I have a very simple function to illustrate yield keyword in python:

def simpleFun():
    yield 1 
    yield 2 
    yield 3 
x=simpleFun() 
print(x.next()) 
print(x.next()) 
print(x.next()) 

which will output

1
2
3

How to write an equivalent function in Julia.

I have seen the 'yield' keyword is used in a different context in Julia. Ref : What does the “yield” keyword do in Julia?


Solution

  • Here is a way that follows the style of the Python code:

    julia> using ResumableFunctions
    
    julia> @resumable function simplefunction()
               @yield 1
               @yield 2
               @yield 3
           end
    simplefunction (generic function with 1 method)
    
    julia> x = simplefunction()
    var"##simplefunction_FSMI#293"(0x00)
    
    julia> print(x())
    1
    julia> print(x())
    2
    julia> print(x())
    3