Effect.ts: Absence as First-Class

StreamsLesson 17 of 51

17. Stream Operations - Lazy Evaluation

Streams are LAZY - they don't execute until you consume them. Just like Effects!

Code Example
// Define a stream (no execution!)
const numbers = Stream.iterate(0, n => n + 1);
// This is INFINITE! But hasn't done anything yet.

// Transform it (still no execution!)
const evens = numbers.pipe(
  Stream.filter(n => n % 2 === 0),
  Stream.take(5)
);

// NOW it executes - only generates what we need
const result = await Effect.runPromise(
  Stream.runCollect(evens)
);
// [0, 2, 4, 6, 8]

// It only computed 10 numbers (0-9),
// not infinity!
Interactive Example
const { Stream } = await import('effect');
const numbers = Stream.iterate(0, n => n + 1);
const evens = numbers.pipe(
      Stream.filter(n => n % 2 === 0),
      Stream.take(5)
);
const result = await Effect.runPromise(Stream.runCollect(evens));
return `Lazy streams!

Defined: Infinite numbers
Filtered: Only evens
Took: First 5

Result: [${Array.from(result).join(', ')}]

Only computed what we needed!`;
Explanation

Lazy streams: describing sequential absence without execution.

Traditional approach: generate all values upfront. Stream types infinite unavailability:

  • Infinite numbers are unavailable
  • Transform the unavailable sequence
  • Still no execution - just describing absence
  • Execute only when consumed

Absence-first laziness: infinite data that doesn't exist until needed!


Part 17 of 51 in the Effect.ts Absence Modeling series