LazyList 만들기
지연 수열을 구성해 보세요.
LazyList 만들기은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
자주 묻는 질문
“LazyList 만들기” 강의는 무료인가요?
네 — “LazyList 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“LazyList 만들기”에서 뭘 배우나요?
지연 수열을 구성해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“LazyList 만들기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 지연성 이해하기
- LazyList 만들기
- 무한 스트림
- 지연 방식으로 가져오고 필터링하기