Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #319 Generator function

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

import java.util.function.Function;
class G<T> {
    T t;
    Function<T, T> f;
    G(T t, Function<T, T> f) {
        this.t = t;
        this.f = f;
    }
    T yield() {
        return t = f.apply(t);
    }
}
import static java.lang.System.out;
import java.util.Random;
import java.util.function.Supplier;
record G<T>(Supplier<T> s) {
    T yield() {
        return s.get();
    }
}
Random r = new Random();
G<?> g = new G<>(r::nextInt);
int x = g.yield();
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
}
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

New implementation...
< >
willard