Note that the behavior seems to be different depending on the language.
C# ##
using System;
using System.Collections.Generic;
class Program {
static IEnumerable<string> Three() {
yield return "one";
yield return "two";
yield return "three";
}
static void Main() {
var co = Three();
Console.WriteLine("1");
foreach (var x in co)
Console.WriteLine(x);
Console.WriteLine("2");
foreach (var x in co)
Console.WriteLine(x);
}
}
Execution result:
1
one
two
three
2
one
two
three
JavaScript(Node)
"use strict"
function* three() {
yield "one";
yield "two";
yield "three";
}
function main() {
var co = three();
console.log("1");
for (let x of co)
console.log(x);
console.log("2");
for (let x of co)
console.log(x);
}
main();
Execution result:
1
one
two
three
2
Julia
function three()
produce("one")
produce("two")
produce("three")
end
function main()
co = @task three()
println("1")
for x = co
println(x)
end
println("2")
for x = co
println(x)
end
end
main()
Execution result:
1
one
two
three
2
Lua
function three()
coroutine.yield("one")
coroutine.yield("two")
coroutine.yield("three")
end
function main()
co = coroutine.wrap(three)
print("1")
for x in co do
print(x)
end
print("2")
for x in co do
print(x)
end
end
main()
Execution result:
1
one
two
three
2
lua: a.lua:17: cannot resume dead coroutine
stack traceback:
[C]: in function 'for iterator'
a.lua:17: in function 'main'
a.lua:23: in main chunk
[C]: in ?
Python
def three():
yield "one"
yield "two"
yield "three"
def main():
co = three()
print("1")
for x in co:
print(x)
print("2")
for x in co:
print(x)
main()
Execution result:
1
one
two
three
2
Postscript:
There are also the following methods.
class three:
def __iter__(self):
yield "one"
yield "two"
yield "three"
Execution result:
1
one
two
three
2
one
two
three
Ruby
def three
Enumerator.new do |y|
y << "one"
y << "two"
y << "three"
end
end
def main
co = three()
puts "1"
for x in co
puts x
end
puts "2"
for x in co
puts x
end
end
main
Execution result
1
one
two
three
2
one
two
three
In C # and Ruby, if the same coroutine is reused in the for statement, it behaves as if it is extracted from the beginning of the element. In JavaScript (Node), Julia, Lua, and Python, coroutines behaved as if they were used up and could not be reused.
Recommended Posts