How does LazyList.fill(n) actually works in Scala?

82 Views Asked by At

I'm trying to understand how does the LazyList.fill actually works. I implemented a retry logic using LazyList.fill(n). But seems like it is not working as expected.

def retry[T](n: Int)(block: => T): Try[T] = {
  val lazyList = LazyList.fill(n)(Try(block))
  lazyList find (_.isSuccess) getOrElse lazyList.head
}

Considering the above piece of code, I am trying to execute block with a retry logic. If the execution succeeds, return the result from block else retry until it succeeds for a maximum of n attempts.

Is it like LazyList will evaluate the first element and if it finds true, it skips the evaluation for the remaining elements in the list?

1

There are 1 best solutions below

2
sarveshseri On

As I already mentiond in the comment, this is exactly what a LazyList is supposed to do.

The elements in a LazyList are also materialized/computed only when there is demand from an actual consumer.

And find method of LazyList respect this lazyness. You can find it cleary written in documentation as well - https://www.scala-lang.org/api/2.13.x/scala/collection/immutable/LazyList.html#find(p:A=%3EBoolean):Option[A]

def find(p: (A) => Boolean): Option[A]

// Finds the first element of the lazy list satisfying a predicate, if any.

// Note: may not terminate for infinite-sized collections.

// This method does not evaluate any elements further than the first element matching the predicate.

So, If the first element succeeds, it will stop at the first element itself.

Also, if you are writing a retry method then you probably also want to stop at first success. Why would you want to continue evaluating the block even after the suceess.

You might want to better clarify your exact requirements to get a more helpful answer.