Generators and Lazy Evaluation

Are values produced on demand or precomputed — PHP's lazy yield taught across 10 languages and four schools.

C C23

C23
#include <stdio.h>

/* C has no generators: hand-write a state-machine struct plus a next function */
typedef struct {
    int i;     /* current cursor (the state) */
    int limit; /* upper bound */
    int done;  /* exhausted flag */
} SquaresGen;

int squares_next(SquaresGen *g, int *out) {
    if (g->done) return 0; /* exhausted */
    *out = g->i * g->i;    /* computed only when requested (lazy) */
    g->i++;
    if (g->i > g->limit) g->done = 1;
    return 1;
}

int main(void) {
    SquaresGen g = {1, 4, 0}; /* building the state machine computes nothing */
    int v;
    int first = 1;
    printf("created, nothing ran yet\n");
    while (squares_next(&g, &v)) { /* each call advances one step */
        printf(first ? "%d" : " %d", v);
        first = 0;
    }
    printf("\n");
    return 0;
}
Output
created, nothing ran yet
1 4 9 16

C++ C++26

C++26
#include <coroutine>
#include <cstdio>
#include <string>

// C++20 coroutines: co_yield suspends and hands out a value, then resumes here
template <typename T>
struct Generator {
    struct promise_type {
        T current;
        Generator get_return_object() {
            return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        std::suspend_always initial_suspend() noexcept { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        std::suspend_always yield_value(T v) { current = v; return {}; }
        void return_void() {}
        void unhandled_exception() {}
    };

    std::coroutine_handle<promise_type> h;
    explicit Generator(std::coroutine_handle<promise_type> hh) : h(hh) {}
    ~Generator() { if (h) h.destroy(); }

    bool next() { h.resume(); return !h.done(); } // advance to the next co_yield
    T value() const { return h.promise().current; }
};

Generator<int> squares(int limit) {
    for (int i = 1; i <= limit; ++i) {
        co_yield i * i; // suspension point: the value is produced on demand
    }
}

int main() {
    auto gen = squares(4); // constructing the coroutine computes nothing yet
    std::string out;
    bool first = true;
    while (gen.next()) {
        if (!first) out += " ";
        out += std::to_string(gen.value());
        first = false;
    }
    std::printf("created, nothing ran yet\n%s\n", out.c_str());
    return 0;
}
Output
created, nothing ran yet
1 4 9 16

C# v11.0.100

v11.0.100
IEnumerable<int> Squares(int limit) {
    for (int i = 1; i <= limit; i++) {
        yield return i * i; // pause here; the value is produced only when pulled
    }
}

var gen = Squares(4); // calling runs NOTHING yet: only a state machine is returned
Console.WriteLine("created, nothing ran yet");

var pulled = new List<int>();
foreach (var v in gen) { // each MoveNext resumes the body until the next yield
    pulled.Add(v);
}
Console.WriteLine(string.Join(" ", pulled));
Output
created, nothing ran yet
1 4 9 16

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
)

// Go has no yield syntax; the idiomatic model is goroutine + channel:
// values are produced on demand, and receiving is consuming.
func squares(limit int) <-chan int {
	ch := make(chan int)
	go func() {
		defer close(ch)
		for i := 1; i <= limit; i++ {
			ch <- i * i // send blocks: production pauses until the value is received
		}
	}()
	return ch
}

func main() {
	ch := squares(4)
	fmt.Println("created, nothing ran yet")

	out := make([]string, 0, 4)
	for v := range ch { // range keeps pulling until the channel is closed
		out = append(out, fmt.Sprintf("%d", v))
	}
	fmt.Println(strings.Join(out, " "))
}
Output
created, nothing ran yet
1 4 9 16

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        // Java has no yield: Stream pipelines are lazy — intermediate ops do
        // nothing until a terminal operation pulls the values
        Stream<Integer> gen = Stream.iterate(1, i -> i + 1)
                .limit(4)
                .map(i -> i * i);
        System.out.println("created, nothing ran yet");

        List<Integer> computed = gen.toList(); // the pipeline runs here
        List<String> out = new ArrayList<>();
        for (Integer v : computed) {
            out.add(String.valueOf(v));
        }
        System.out.println(String.join(" ", out));
    }
}
Output
created, nothing ran yet
1 4 9 16

JavaScript v26.13.1

v26.13.1
function* squares(limit) {
  for (let i = 1; i <= limit; i++) {
    yield i * i; // pause here; the value is produced only when pulled
  }
}

const gen = squares(4); // calling a generator function runs NOTHING yet
console.log("created, nothing ran yet");

const out = [];
for (const v of gen) { // each for..of step resumes the body until the next yield
  out.push(v);
}
console.log(out.join(" "));
Output
created, nothing ran yet
1 4 9 16

PHP v8.6.0

v8.6.0
function squares(int $limit): Generator {
    for ($i = 1; $i <= $limit; $i++) {
        yield $i * $i; // pause here; the value is produced only when pulled
    }
}

$gen = squares(4); // calling a generator function runs NOTHING yet
echo "created, nothing ran yet\n";

$out = [];
foreach ($gen as $v) { // each foreach step resumes the body until the next yield
    $out[] = $v;
}
echo implode(" ", $out), "\n";
Output
created, nothing ran yet
1 4 9 16

Python v3.15.2

v3.15.2
def squares(limit):
    for i in range(1, limit + 1):
        yield i * i  # pause here; the value is produced only when pulled

gen = squares(4)  # calling a generator function runs NOTHING yet
print("created, nothing ran yet")

out = []
for v in gen:  # each iteration resumes the body until the next yield
    out.append(v)
print(" ".join(str(v) for v in out))
Output
created, nothing ran yet
1 4 9 16

Rust v1.99.1

v1.99.1
// Rust has no yield syntax; laziness lives in the Iterator trait: adapter
// chains are lazy and only compute when a consumer drives them
fn squares(limit: i32) -> impl Iterator<Item = i32> {
    (1..=limit).map(|i| i * i) // nothing runs here; an iterator is just built
}

fn main() {
    let it = squares(4);
    println!("created, nothing ran yet");
    let out: Vec<String> = it.map(|v| v.to_string()).collect(); // values computed now
    println!("{}", out.join(" "));
}
Output
created, nothing ran yet
1 4 9 16

TypeScript v26.13.1

v26.13.1
function* squares(limit: number): Generator<number> {
  for (let i = 1; i <= limit; i++) {
    yield i * i; // pause here; the value is produced only when pulled
  }
}

const gen = squares(4); // calling a generator function runs NOTHING yet
console.log("created, nothing ran yet");

const out: number[] = [];
for (const v of gen) { // each for..of step resumes the body until the next yield
  out.push(v);
}
console.log(out.join(" "));
Output
created, nothing ran yet
1 4 9 16

Language differences

C: no generators — the idiom is a hand-written state-machine struct plus a next function (example): state kept explicitly, laziness guaranteed by the calling rhythm; heavy boilerplate, and no natural in-loop style.

C++: C++20 coroutines are generators via co_yield (example ships a minimal Generator scaffold); the standard library gained std::generator in C++23 — before that you wrap coroutines yourself.

C#: a yield return method returns IEnumerable<T> and the compiler builds a state machine (example); yield break plays return; calling the method runs nothing — enumeration drives it.

Go: no yield — the idiom is goroutine + channel (example): receiving is consuming, blocking sends give backpressure; the key difference: this is a concurrency model (values across goroutines), not suspend/resume inside a function, and forgetting close deadlocks.

Java: no yield — Stream pipelines are lazy (example): intermediate ops just record, terminal ops (toList/forEach) pull; but there is no suspend/resume semantics — a Stream cannot pause midway and resume on the same spot.

JavaScript: function* + yield, isomorphic to PHP (example): returns a Generator object, for..of drives it step by step; yield* delegates to a sub-generator.

PHP: yield makes the function return a Generator (implements Iterator) (example): calling a generator function runs no body code, each foreach step advances to the next yield; yield from delegates and getReturn() fetches the return value; the laziness win: big sequences no longer hog memory wholesale.

Python: yield turns a function into a generator function (example), returning a generator iterator — a near one-to-one match with PHP; generator expressions (x*x for x in xs) also exist.

Rust: no yield syntax — laziness lives in the Iterator trait (example): adapters (map/filter) are lazy by default and consumers (for/collect) drive evaluation; this is combinator + trait rather than syntax + suspension, so custom lazy sequences implement Iterator::next.

TypeScript: identical to JS (function* + yield) (example), with Generator<T> annotating the produced type.