Construire une LazyList
Construisez des suites paresseuses.
Construire une LazyList est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Scala for Backend Engineering & Functional Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Construction Basics
There are several ways to build a LazyList. The simplest is the apply factory, just like building a List.
But the real power comes from constructors that keep the tail lazy, which we will explore in this lesson.
val ll = LazyList(10, 20, 30)
println(ll.head)The Empty LazyList
LazyList.empty is the terminator, the lazy equivalent of Nil. Every finite LazyList ends with it.
You use it as the base case when prepending elements with #::.
object Demo extends App {
val empty = LazyList.empty[Int]
println(empty.isEmpty)
println(empty.toList)
}Prepending with #::
The #:: operator cons a head onto a by-name tail. Build a list right to left, ending with LazyList.empty.
Because #:: takes its tail lazily, nothing past the head is built until forced.
object Demo extends App {
val ll = 1 #:: 2 #:: 3 #:: LazyList.empty
println(ll.toList)
}Watching Laziness
Put a side effect in the tail to see when it runs. Only forcing the tail triggers it.
Run this: "building tail" prints only after you access the second element, not when the LazyList is defined.
object Demo extends App {
val ll = 1 #:: { println("building tail"); 2 #:: LazyList.empty }
println("defined")
println(ll.head)
println(ll(1))
}cons Explicitly
Under the hood #:: is LazyList.cons. Both the head and tail are by-name in cons, giving full control over evaluation.
This is useful when defining recursive generators.
val ll = LazyList.cons(1, LazyList.cons(2, LazyList.empty))
println(ll.head)Recursive Generators
A LazyList can refer to itself. Define a function that produces a head and recursively calls itself for the tail.
Because the tail is by-name, the recursion does not run forever; it pauses until each cell is demanded.
def countFrom(n: Int): LazyList[Int] =
n #:: countFrom(n + 1)
println(countFrom(5).take(3).toList)Running a Generator
Let's run a self-referential generator and pull a few values. take limits how many cells are forced.
Without take this would loop forever, so always bound an infinite generator before forcing it.
object Demo extends App {
def countFrom(n: Int): LazyList[Int] =
n #:: countFrom(n + 1)
println(countFrom(1).take(5).toList)
}From an Iterator
You can wrap an existing collection or iterator. LazyList.from(start) builds an infinite count, and someList.to(LazyList) converts eagerly known data.
These give a lazy view over data you already have or can describe.
object Demo extends App {
val ll = List(1, 2, 3).to(LazyList)
println(ll.map(_ * 2).toList)
}LazyList.iterate
LazyList.iterate(seed)(f) repeatedly applies f to build each next element from the previous one.
It is a clean way to express sequences defined by a step rule, like powers of two.
object Demo extends App {
val powers = LazyList.iterate(1)(_ * 2)
println(powers.take(6).toList)
}LazyList.continually
LazyList.continually(expr) repeats an expression endlessly, re-evaluating it for each element. Handy for constant or randomized streams.
Combine with take to grab a finite slice.
object Demo extends App {
val zeros = LazyList.continually(0)
println(zeros.take(4).toList)
}Choosing a Constructor
Use apply for fixed small lists, #:: or cons for hand-written recursion, iterate for step rules, from for counting, and continually for repetition.
All keep the tail lazy, so the choice is about expressiveness.
Quick Check
Check your grasp of LazyList construction.
Recap
You built LazyLists with apply, empty, #::/cons, iterate, from, and continually.
The by-name tail makes self-referential, potentially infinite generators safe to define. Next we lean into that to create truly infinite streams.
Questions Fréquemment Posées
La leçon « Construire une LazyList » est-elle gratuite ?
Oui — le texte complet de « Construire une LazyList » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Scala for Backend Engineering & Functional Programming, passe à CoddyKit PRO. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Construire une LazyList » ?
Construisez des suites paresseuses. Tu pratiques Scala for Backend Engineering & Functional Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Scala for Backend Engineering & Functional Programming ?
Aucune expérience préalable n'est requise. Scala for Backend Engineering & Functional Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.
Combien de temps prend la leçon « Construire une LazyList » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Scala for Backend Engineering & Functional Programming ?
Oui. Chaque leçon Scala for Backend Engineering & Functional Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- La paresse expliquée
- Construire une LazyList
- Flux infinis
- Prendre et filtrer paresseusement