Logo

Programming-Idioms

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

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++;
  }
}

Infinite lazy list of ints starting from a specific integer

New implementation...
< >
willard