How to make a list lazy, i.e. create a LazyList given a usual one? I tried to find suitable method in Scala documentation, but there is no such function.
How to convert List to LazyList?
Asked Answered
One way would be to unpack the list into a LazyList. For example:
LazyList(List(1,2,3) :_*)
Are you sure this works like you think for very large lists? IOW, how is it different, more preferable, or less desirable than using the
.to(LazyList)
approach in my answer: https://mcmap.net/q/1564229/-how-to-convert-list-to-lazylist –
Misdirect From your own example, substituting val validChars = LazyList(('A' to 'Z') :_*) works fine. Perhaps you can state what specifically you think is wrong with it? As far as style, it's just different to yours. –
Bismarck
To those Asking, "What's the point of wrapping an already computed Seq
or List
with a LazyList
?"
Answer: Inferred type propagation
Example without LazyList
which causes an OOME (OutOfMemoryException):
val validChars = //List[Char]
('A' to 'Z')
.toList
val allCodes =
for {
a <- validChars
b <- validChars
c <- validChars
d <- validChars
e <- validChars
f <- validChars
g <- validChars
h <- validChars
i <- validChars
j <- validChars
} yield s"$a$b$c$d$e$f$g$h$i"
Example with LazyList
enabling all sorts of stream-like approaches without generating an OOME:
val validChars = //LazyList[Char]
('A' to 'Z')
.to(LazyList)
val allCodes =
for {
a <- validChars
b <- validChars
c <- validChars
d <- validChars
e <- validChars
f <- validChars
g <- validChars
h <- validChars
i <- validChars
j <- validChars
} yield s"$a$b$c$d$e$f$g$h$i"
Another option is to change the first line of the for
comprehension to:
a <- validChars.to(LazyList)
© 2022 - 2025 — McMap. All rights reserved.
list.to(LazyList)
- in any case, what is the point? it is already computed. – ScarifymyList.view
will create a lazySeqView
so that future traversals will be lazy. – Almsgiverview
oriterator
would have been better in this case. That is why I asked OP what was the end goal. – Scarify