Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>By defining those utility functions</p> <pre><code>implicit def eitherOps[E, A](v: Either[E, A]) = new { def map[B](f: A =&gt; B) = v match { case Left(e) =&gt; Left(e) case Right(a) =&gt; Right(f(a)) } def flatMap[B](f: A =&gt; Either[E, B]) = v match { case Left(e) =&gt; Left(e) case Right(a) =&gt; f(a) } def or(a: A) = v match { case Left(_) =&gt; Right(a) case x =&gt; x } } def secure[A, B](f: A =&gt; B) = new { def run(a: A): Either[Trowable, B] = try { Right(f(a)) } catch { case e =&gt; Left(e) } } </code></pre> <p>and simplifying yours</p> <pre><code>def fA(s : String) = 7 def fB(i : Int) = 1.0 def fC(d : Double) = true </code></pre> <p>We'll have:</p> <pre><code>def test(s: String): Either[Throwable, Double] = for { a &lt;- secure(fA).run(s).or(0) b &lt;- secure(fB).run(a).or(0.0) c &lt;- secure(fC).run(b).or(false) } yield result(a, b, c) </code></pre> <p><strong>Edit</strong></p> <p>Here's an executable but sadly, more verbose code snippet</p> <pre><code>object Example { trait EitherOps[E, A] { def self: Either[E, A] def map[B](f: A =&gt; B) = self match { case Left(e) =&gt; Left(e) case Right(a) =&gt; Right(f(a)) } def flatMap[B](f: A =&gt; Either[E, B]) = self match { case Left(e) =&gt; Left(e) case Right(a) =&gt; f(a) } def or(a: A) = self match { case Left(_) =&gt; Right(a) case x =&gt; x } } trait SecuredFunction[A, B] { def self: A =&gt; B def secured(a: A): Either[Throwable, B] = try { Right(self(a)) } catch { case e =&gt; Left(e) } } implicit def eitherOps[E, A](v: Either[E, A]) = new EitherOps[E, A] { def self = v } implicit def opsToEither[E, A](v: EitherOps[E, A]) = v.self implicit def secure[A, B](f: A =&gt; B) = new SecuredFunction[A, B]{ def self = f } def fA(s : String) = 7 def fB(i : Int) = 1.0 def fC(d : Double) = true def result(i : Int, d : Double, b : Boolean) = { if (b) d else i } def test(s: String): Either[Throwable, Double] = for { a &lt;- (fA _).secured(s) or 0 b &lt;- (fB _).secured(a) or 0.0 c &lt;- (fC _).secured(b) or false } yield result(a, b, c) } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload