Skip to content

Instantly share code, notes, and snippets.

@lyricallogical
Created April 18, 2012 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyricallogical/2415136 to your computer and use it in GitHub Desktop.
Save lyricallogical/2415136 to your computer and use it in GitHub Desktop.
特に面白みはない
trait Zero[A] { val zero: A }
implicit val IntZero = new Zero[Int] { val zero = 0 }
implicit def RightProjectionWithFilter[A, B](r: Either.RightProjection[A, B])(implicit azero: Zero[A]) = new {
class WithFilter(p: B => Boolean) {
def map[C](f: B => C): Either[A, C] = r.filter(p).getOrElse(Left(azero.zero)).right.map(f)
def flatMap[AA >: A, C](f: B => Either[AA, C]): Either[AA, C] = r.filter(p).getOrElse(Left(azero.zero)).right.flatMap(f)
def withFilter(p0: B => Boolean): WithFilter = new WithFilter(b => p(b) && p0(b))
}
def withFilter(p: B => Boolean): WithFilter = new WithFilter(p)
}
for { x <- Right[Int, Int](1).right if x > 0; y <- Right(2).right } yield x + y // => Right(3)
for { x <- Right[Int, Int](1).right if x > 1; y <- Right(2).right } yield x + y // => Left(0)
@lyricallogical
Copy link
Author

型が Nothing だとダメなので Right.apply 使う場合は型明示する必要あり。だるい。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment