-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add reject
(partial function) method to MonadError
#2194
Conversation
Oh hang on tests still need attention. I will revisit this after I have fixed them. |
Thanks for this. The method seems useful, but I do agree that |
Thanks for taking a look. I've renamed it to Re: binary compatibility, mea cupla, I forgot adding a method to a trait isn't safe prior to Scala 2.12. |
Codecov Report
@@ Coverage Diff @@
## master #2194 +/- ##
==========================================
+ Coverage 94.78% 94.78% +<.01%
==========================================
Files 332 332
Lines 5697 5699 +2
Branches 214 214
==========================================
+ Hits 5400 5402 +2
Misses 297 297
Continue to review full report at Codecov.
|
@@ -16,6 +16,9 @@ final class MonadErrorOps[F[_], E, A](val fa: F[A]) extends AnyVal { | |||
def ensureOr(error: A => E)(predicate: A => Boolean)(implicit F: MonadError[F, E]): F[A] = | |||
F.ensureOr(fa)(error)(predicate) | |||
|
|||
def reject(pf: PartialFunction[A, E])(implicit F: MonadError[F, E]): F[A] = | |||
F.flatMap(fa)(a => if (pf.isDefinedAt(a)) F.raiseError(pf(a)) else F.pure(a)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is this trick that avoids calling isDefinedAt
and then apply
of the PartialFunction
, maybe worthwhile to copy here, just a thought. Also, instead of F.pure(a)
shall we just return fa
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm thinking of doing F.flatMap(fa)(a => pf.andThen(F.raiseError[A]).applyOrElse(a, _ => fa))
, though that does create a new "AndThen" object. Is avoiding the allocation important?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
that might be a good balance between readability and performance.
reject
(partial function) method to MonadError
Partial functions are a convenient method for expressing
ensure
.In ApplicativeError
handleError
has another methodrecover
which acceptsPartialFunction
. This is similar but for the reverse direction. If you can think of a better name thanensureP
I'm open to it - perhapsreject
,guard
orguarantee
.