Search code examples
scalascala-catscats-effect

How to traverse List[IO] to execute everything and collect all errors?


For example I have a list of IO with some errors.

def print(x: Int) = {
  if(x == 3 || x == 4) 
    IO.raiseError(new RuntimeException("error " + x))
  else 
    IO(println(x))
}

List.range(1,6).map(print)

If I use traverse

List.range(1,6).map(print)

It prints only 1,2 and I can get one error "error 3" I would like to print all numbers

1 
2
5

and get list of all errors

List("error 3", "error 4")

How can I do this?


Solution

  • The solution:

    List.range(1, 6).traverse(print(_).attempt)
       .map(_.collect{case Left(x) => x})