Logo

Programming-Idioms

Write a function g that behaves like an iterator.
Explain if it can be used directly in a for loop.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
List<int> g(int start) sync* {
  while (true) {
    yield start;
    start++;
  }
}
func generator() chan int {
	ch := make(chan int, 16)
	go func() {
		defer close(ch)
		timeout := time.After(2 * time.Minute)
		
		for i := 0; i < 1024; i++ {
			select {
			case ch <- i:
			case <-timeout:
				return
			}
		}
	}()
	return ch
}
import static java.util.stream.Stream.generate;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Stream;
Random r = new Random();
Supplier<Integer> s = r::nextInt;
Stream<Integer> g = generate(s);
import static java.util.stream.Stream.iterate;
import java.util.stream.Stream;
Stream<?> g = iterate(0, i -> i + 1).limit(100);
sub _upto (&) { return $_[0]; }  # prototype & is for a function param
sub upto {
    my ($start, $end) = @_;

    my $n = $start;

    return _upto {
        return
            wantarray ? $start .. $end    :
            $n > $end ? ($n = $start, ()) :
            $n++
            ;
        };
}
my $it = upto(3, 5);
foreach ( $it->() ) { print ' ' . $_ }
def g():
    for i in range(6):
        yield i
g = (1..6).each