Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 283
gurghet Avatar asked Feb 01 '26 23:02

gurghet


1 Answers

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 + _)
  )
}
like image 196
St.Antario Avatar answered Feb 04 '26 14:02

St.Antario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!