gurghet
gurghet

Reputation: 7706

How to correctly write a foldLeft function that may fail?

Consider the following snippet

def sayManyTimes(a: String): IO[String] = IO(a * 3)    
(1 to 2).foldLeft("Read this: ")((c, i) => 
    c + sayManyTimes("mayo").unsafeRunSync)

Now, this achieves the desired result, but is not ideal because it’s an unsafe operation.

I would like to restructure the code so that the second line, instead of returning the string, returns the IO that will create the string.

Upvotes: 3

Views: 85

Answers (1)

St.Antario
St.Antario

Reputation: 27435

So what's wrong with the for-comprehension?

(1 to 2).foldLeft(IO("Read this: "))((c, i) =>
  for {
    cc <- c
    smt <- sayManyTimes("mayo")
  } yield cc + smt)

You can also expand for-comprehension manually:

(1 to 2).foldLeft(IO("Read this: ")){ (c, _) =>
  c.flatMap(cc => 
    sayManyTimes("mayo").map(cc + _)
  )
}

Upvotes: 2

Related Questions