This is a followup to my previous question. Suppose I have the following functions:
type Result[A] = Either[String, A] // left is an error message
def f1(a: A): Result[B] = ...
def f2(b: B): Result[C] = ...
def f3(c: C): Result[D] = ...
def f(a: A): Result[D] = for {
b <- f1(a).right
c <- f2(b).right
d <- f3(c).right
} yield d;
Suppose also I would like to add more information to the error message.
def f(a: A): Result[D] = for {
b <- { val r = f1(a); r.left.map(_ + s"failed with $a"); r.right }
c <- { val r = f2(b); r.left.map(_ + s"failed with $a and $b"); r.right }
d <- { val r = f3(c); r.left.map(_ + s"failed with $a, $b, and $c"); r.right }
} yield d;
The code looks ugly. How would you suggest improve the code ?