lazy et Enumerator : le modèle mental du calcul tiré par la demande en Ruby lazy and Enumerator: the mental model of demand-driven computation in Ruby

Une chaîne stricte calcule tout à chaque maillon ; lazy diffère et ne produit que ce qu'on demande, d'où l'infini calculable. Sous lazy, l'Enumerator. Ruby 3.4.A strict chain computes everything at each link; lazy defers and only produces what's asked for, hence computable infinity. Under lazy, the Enumerator. Ruby 3.4.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
EnumerableEnumerable
PubliéPublished

En bref. Une chaîne stricte pousse tout à chaque maillon ; lazy attend qu’on tire.

Le modèle en une phrase

lazy ne calcule rien tant qu’on ne tire pas : les éléments descendent la chaîne un à un, et on s’arrête dès qu’on en a assez.

In short. A strict chain pushes everything through each link; lazy waits to be pulled.

The model in one sentence

lazy computes nothing until you pull: elements flow down the chain one by one, and it stops as soon as there are enough.

(1..10).map { _1 * 2 }
.select { _1 % 3 == 0 }.first(3)
Calcul poussé ou tiréPushed or pulled computation10 traités10 traités12345678910strict : 10 éléments traitéshachuré = jamais calculéhatched = never computedvérifié avec Ruby 3.4checked with Ruby 3.4
  1. (1..10).map { _1 * 2 } — Strict : map traite les dix éléments et matérialise un tableau.Strict: map processes all ten elements and builds an array.
  2. .select { _1 % 3 == 0 }.first(3) — On n'en voulait que trois, mais les dix sont déjà calculés : [6, 12, 18].We only wanted three, but all ten are already computed: [6, 12, 18].
Une chaîne stricte pousse tout à chaque maillon. lazy attend qu'on tire : les éléments descendent un à un, et on s'arrête dès qu'on en a assez.A strict chain pushes everything through each link. lazy waits to be pulled: elements flow down one by one, and it stops as soon as there are enough.

La preuve, avec Ruby 3.4

seen = []
r = (1..Float::INFINITY).lazy
      .map { seen << _1; _1 * 2 }
      .select { _1 % 3 == 0 }
      .first(3)
p r      # => [6, 12, 18]
p seen   # => [1, 2, 3, 4, 5, 6, 7, 8, 9]

Sur l’infini, neuf éléments seulement ont été touchés. En strict sur (1..10), les dix le sont, pour le même résultat.

L’Enumerator, dessous

e = [10, 20, 30].each
p e.next, e.peek, e.next, e.next   # => 10, 20, 20, 30
e.next
StopIteration: iteration reached an end

Et on fabrique sa propre suite infinie :

fib = Enumerator.new { |y| a, b = 0, 1; loop { y << a; a, b = b, a + b } }
p fib.take(8)                       # => [0, 1, 1, 2, 3, 5, 8, 13]
p fib.lazy.select(&:even?).first(4) # => [0, 2, 8, 34]

Ce que l’image cache

lazy n’est pas gratuit : chaque élément traverse des appels de bloc supplémentaires. Sur dix éléments, l’overhead dépasse le gain ; il paie sur de grandes ou infinies séquences, ou quand on sort tôt.

Pour aller plus loin

Le numéro ci-dessous détaille lazy et les Enumerator (next, peek, Enumerator.new), avec des exercices.

The proof, with Ruby 3.4

seen = []
r = (1..Float::INFINITY).lazy
      .map { seen << _1; _1 * 2 }
      .select { _1 % 3 == 0 }
      .first(3)
p r      # => [6, 12, 18]
p seen   # => [1, 2, 3, 4, 5, 6, 7, 8, 9]

On infinity, only nine elements were touched. Strict on (1..10) touches all ten, for the same result.

The Enumerator, underneath

e = [10, 20, 30].each
p e.next, e.peek, e.next, e.next   # => 10, 20, 20, 30
e.next
StopIteration: iteration reached an end

And you can build your own infinite sequence:

fib = Enumerator.new { |y| a, b = 0, 1; loop { y << a; a, b = b, a + b } }
p fib.take(8)                       # => [0, 1, 1, 2, 3, 5, 8, 13]
p fib.lazy.select(&:even?).first(4) # => [0, 2, 8, 34]

What the picture hides

lazy isn’t free: each element goes through extra block calls. On ten elements, the overhead exceeds the gain; it pays off on large or infinite sequences, or when you exit early.

Go deeper

The issue below details lazy and Enumerator (next, peek, Enumerator.new), with exercises.

Questions fréquentesFrequently asked questions

Que fait lazy en Ruby ?What does lazy do in Ruby?

Il rend un Enumerator::Lazy qui diffère le calcul : rien ne s'exécute avant qu'on tire (first, to_a, force), et les éléments descendent la chaîne un à un.It returns an Enumerator::Lazy that defers computation: nothing runs until you pull (first, to_a, force), and elements flow down the chain one by one.

Comment calculer sur une séquence infinie ?How do I compute over an infinite sequence?

Avec lazy : (1..Float::INFINITY).lazy.map { _1 * 2 }.first(3) rend [2, 4, 6]. Sans lazy, le map tournerait indéfiniment.With lazy: (1..Float::INFINITY).lazy.map { _1 * 2 }.first(3) returns [2, 4, 6]. Without lazy, the map would run forever.

Quelle est la différence entre next et peek sur un Enumerator ?What is the difference between next and peek on an Enumerator?

next rend l'élément suivant et avance ; peek le rend sans avancer. À la fin, next lève StopIteration : iteration reached an end.next returns the next element and advances; peek returns it without advancing. At the end, next raises StopIteration: iteration reached an end.

Comment créer une suite infinie à la main ?How do I build an infinite sequence by hand?

Avec Enumerator.new : un bloc qui pousse des valeurs dans un yielder (y << a). Fibonacci tient en une ligne, et fib.take(8) rend [0, 1, 1, 2, 3, 5, 8, 13].With Enumerator.new: a block that pushes values into a yielder (y << a). Fibonacci fits on one line, and fib.take(8) returns [0, 1, 1, 2, 3, 5, 8, 13].

Faut-il mettre lazy partout ?Should I put lazy everywhere?

Non : sur dix éléments, la machinerie de lazy coûte plus qu'elle ne rapporte. Réserve-le aux grandes ou infinies séquences, ou aux sorties anticipées.No: on ten elements, lazy's machinery costs more than it saves. Keep it for large or infinite sequences, or early exits.

RubylazyEnumeratorItérationModèle mental

← Tous les articlesAll articles