Created
March 9, 2013 05:04
-
-
Save stew/5122619 to your computer and use it in GitHub Desktop.
uncozip
This file contains 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
object Uncozip { | |
implicit val wtf = language.higherKinds | |
trait Sum2[F[_, _]] { | |
def cata[A, B, X](a: A ⇒ X, b: B ⇒ X)(fab: F[A, B]): X | |
} | |
implicit val sumEither: Sum2[Either] = new Sum2[Either] { | |
def cata[A, B, X](a: A ⇒ X, b: B ⇒ X)(fab: Either[A, B]): X = { | |
fab match { | |
case Left(l) ⇒ a(l) | |
case Right(r) ⇒ b(r) | |
} | |
} | |
} | |
implicit val sumEitherz: Sum2[\/] = new Sum2[\/] { | |
def cata[A, B, X](a: A ⇒ X, b: B ⇒ X)(fab: A \/ B): X = { | |
fab.fold(a(_), b(_)) | |
} | |
} | |
implicit val sumValidation: Sum2[Validation] = new Sum2[Validation] { | |
def cata[A, B, X](a: A ⇒ X, b: B ⇒ X)(fab: A Validation B): X = { | |
fab.fold(a(_), b(_)) | |
} | |
} | |
abstract class Uncozips[F[_], G[_, _], A, B](fab: F[G[A, B]]) { | |
def uncozip: (F[A], F[B]) | |
} | |
implicit def uncozip[F[_]: Foldable, G[_, _], A, B](fab: F[G[A, B]])(implicit g: Sum2[G], mfa: ApplicativePlus[F], mfb: ApplicativePlus[F]): Uncozips[F, G, A, B] = new Uncozips[F, G, A, B](fab) { | |
def uncozip = { | |
implicitly[Foldable[F]].foldRight[G[A, B], (F[A], F[B])](fab, (mfa.empty, mfb.empty)) { (l, r) ⇒ | |
g.cata[A, B, (F[A], F[B])]({ (a: A) ⇒ (mfa.plus(mfa.point(a), r._1), r._2) }, | |
{ (b: B) ⇒ (r._1, mfa.plus(mfa.point(b), r._2)) })(l) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment