0Pricing
Scala for Backend Engineering & Functional Programming · Aula

Fluxos infinitos

Modele dados intermináveis com segurança.

Fluxos infinitos é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Infinity, Safely

A LazyList can describe an infinite sequence because its tail is never computed until demanded. You only ever materialize the prefix you consume.

This lets you model natural numbers, primes, or sensor readings without bounding them up front.

All Natural Numbers

LazyList.from(1) is the infinite sequence 1, 2, 3, ... You can take any finite prefix.

Forcing the whole thing would never finish, so always slice it with take or stop with a predicate.

object Demo extends App {
  val nats = LazyList.from(1)
  println(nats.take(5).toList)
}

from with a Step

LazyList.from(start, step) counts by an interval. Use it for even numbers, ticks, or any arithmetic progression.

The sequence is infinite but each call to take forces only what you ask for.

object Demo extends App {
  val evens = LazyList.from(0, 2)
  println(evens.take(5).toList)
}

Self-Referential Streams

A famous trick: define a LazyList in terms of itself. The Fibonacci sequence can be written by zipping the stream with its own tail.

This works only because the tail stays unevaluated until each cell is pulled.

lazy val fibs: LazyList[Int] =
  0 #:: 1 #:: fibs.zip(fibs.tail).map { case (a, b) => a + b }
// fibs(0)=0, fibs(1)=1, fibs(2)=1 ...

Running Fibonacci

Let's force a prefix of that self-referential Fibonacci stream.

Each new element is computed from earlier, already-memoized ones, so the whole thing stays efficient as you pull more values.

object Demo extends App {
  lazy val fibs: LazyList[Int] =
    0 #:: 1 #:: fibs.zip(fibs.tail).map { case (a, b) => a + b }
  println(fibs.take(10).toList)
}

iterate for Sequences

LazyList.iterate generates an infinite sequence by a step function. Powers, geometric growth, and state machines fit naturally.

Here each element is triple the previous, forever.

object Demo extends App {
  val triples = LazyList.iterate(1)(_ * 3)
  println(triples.take(6).toList)
}

A Prime Sieve

Infinite streams shine for the Sieve of Eratosthenes. Take a head prime, filter its multiples from the rest, and recurse.

The filter is lazy, so primes are produced one at a time as you consume them.

def sieve(s: LazyList[Int]): LazyList[Int] =
  s.head #:: sieve(s.tail.filter(_ % s.head != 0))

val primes = sieve(LazyList.from(2))

Running the Sieve

Now pull the first ten primes from that infinite sieve.

Only enough of the underlying number stream is forced to yield ten primes, demonstrating demand-driven computation.

object Demo extends App {
  def sieve(s: LazyList[Int]): LazyList[Int] =
    s.head #:: sieve(s.tail.filter(_ % s.head != 0))
  val primes = sieve(LazyList.from(2))
  println(primes.take(10).toList)
}

Never Force the Whole Thing

Methods that need the entire sequence, like length, toList on an unbounded stream, or foreach without a stop, will hang on an infinite LazyList.

Always bound first with take, takeWhile, or find.

// DON'T: LazyList.from(1).toList    // hangs forever
val ok = LazyList.from(1).take(3).toList

The Head-Holding Trap

If a val holds the head of an infinite memoizing LazyList and you consume far into it, every forced cell stays alive, leaking memory.

For long traversals, consume via a method without binding the head, or use an Iterator.

Why Infinite Streams Matter

Infinite streams let you separate generation from consumption. The producer describes an endless rule; the consumer decides how much to realize.

This is a powerful functional pattern for pipelines, simulations, and lazy data sources.

Quick Check

Test your understanding of infinite LazyLists.

Recap

Infinite LazyLists work because the tail is demand-driven: from, iterate, self-referential fibs, and the prime sieve all generate endlessly yet realize only what you consume.

Avoid whole-sequence operations and head-holding. Next, we master taking and filtering lazily.

Perguntas Frequentes

A aula “Fluxos infinitos” é grátis?

Sim — o texto completo de “Fluxos infinitos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.

O que vou aprender em “Fluxos infinitos”?

Modele dados intermináveis com segurança. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?

Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Fluxos infinitos”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?

Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. A explicação da avaliação tardia
  2. Construindo uma LazyList
  3. Fluxos infinitos
  4. Obtendo e filtrando de forma tardia
← Voltar para Scala for Backend Engineering & Functional Programming