Created
June 18, 2012 23:50
-
-
Save tonymorris/2951500 to your computer and use it in GitHub Desktop.
How to write filter on Either, if such a thing must exist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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