Skip to content

Instantly share code, notes, and snippets.

@lyricallogical
Created April 18, 2012 16: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/2414620 to your computer and use it in GitHub Desktop.
Save lyricallogical/2414620 to your computer and use it in GitHub Desktop.
なんともならない
def withRight[A, B] = new { def apply[R](f: (Either[A, B] => Either.RightProjection[A, B]) => R) = f(_.right) }
def withLeft[A, B] = new { def apply[R](f: (Either[A, B] => Either.LeftProjection[A, B]) => R) = f(_.left) }
withRight[Int, Int] { implicit ev =>
for {
x <- Right(1)
y <- Right(2)
} yield x + y // => Right(3)
for {
x <- Right(1)
y <- Left(2)
} yield x + y // => Left(2)
}
@lyricallogical
Copy link
Author

型パラメタ A, B を内側の apply に逃がすと、型推論の都合上型が付かなくて死ぬ。
仮に R =:= Either[A, B] に限定したものを書いてやったとしても、Left(2) とかは Either[Int, Nothing] なので、型を教えてあげないと Int + Nothing が解決できない、といわれる(ぐぬぬ)

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