How to write filter on Either, if such a thing must exist
| trait Semigroup[A] { | |
| def op(a1: A, a2: A): A | |
| } | |
| trait Monoid[A] extends Semigroup[A] { | |
| def id: A | |
| } | |
| object EitherFilter { | |
| def filterR[A, B](e: Either[A, B])(p: B => Boolean)(implicit M: Monoid[B]): Either[A, B] = | |
| e match { | |
| case Left(a) => Left(a) | |
| case Right(b) => Right(if(p(b)) M.id else b) | |
| } | |
| def filterL[A, B](e: Either[A, B])(p: A => Boolean)(implicit M: Monoid[A]): Either[A, B] = | |
| e match { | |
| case Left(a) => Left(if(p(a)) M.id else a) | |
| case Right(b) => Right(b) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment