Skip to content

Conversation

@pivovarit
Copy link
Member

@pivovarit pivovarit commented Nov 3, 2025

Introduces a generator for lazy for-comprehension variants that produce intermediate ForLazyN<M> classes for supported monadic types (e.g., Option, Try, Either, etc.).

This addition complements the existing eager for-comprehension generator by introducing a lazy variant.

  • Added generation of ForLazyN<M> classes (arity 2 to N) that:
    • Use one monadic source (ts1) followed by a chain of dependent functions (ts2, ts3, …).
    • Allow lazy composition of monadic operations through nested lambdas.
  • Added corresponding For(...) factory methods for convenient construction.
  • Implemented a recursively generated yield(...) method with proper indentation and block structure for readability.

The generator handles mixed monadic/function parameter patterns such as:

Option<T1> ts1;
Function1<T1, Option<T2>> ts2;
Function2<T1, T2, Option<T3>> ts3;

expands for-comprehension with lazily-evaluated variants, so that the existing is possible:

Option<Integer> result = API.For(
  calculate1(),
  r1 -> calculate2(r1),
  (r1, r2) -> calculate3(r1, r2)).yield((r1, r2, r3) -> r1 + r2 + r3);

The generator enforces that the first argument is always a monadic value, not a function. This is necessary because:

  • The first argument acts as the entry point of the comprehension; it provides the initial context for all later flatMap calls.
  • If ts1 were also a function (e.g., Function0<M<T1>>), Java’s generic type inference fails to resolve chained type variables properly.
  • Subsequent arguments can safely be functions (FunctionN<T1, ..., TN, M<T(N+1)>>), since their input types are already determined by previous monadic values.

related: #3038

@pivovarit pivovarit force-pushed the for-lazy branch 2 times, most recently from 6e859c9 to 3b9dd81 Compare November 3, 2025 11:15
@pivovarit pivovarit changed the title Lazy For() Comprehension Lazy For() Comprehension Generator Nov 3, 2025
@pivovarit pivovarit force-pushed the for-lazy branch 3 times, most recently from 1700254 to 3c418d8 Compare November 3, 2025 12:21
@pivovarit pivovarit marked this pull request as ready for review November 3, 2025 13:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants