Created
September 1, 2019 17:26
-
-
Save LukaJCB/1f239d1aae0f84dbba0e900a11e7d31f to your computer and use it in GitHub Desktop.
Union monoidal functors
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
trait Functor[F[_]] { | |
def map[A, B](fa: F[A])(f: A => B): F[B] | |
} | |
trait UnionMonoidal[F[_]] extends Functor[F] { | |
def union[A, B](fa: F[A], fb: F[B]): F[A | B] | |
def empty[A]: F[A] | |
def combineK[A](x: F[A], y: F[A]): F[A] = union(x, y) | |
def sum[A, B](fa: F[A], fb: F[B]): F[Either[A, B]] = | |
combineK(map(fa)(Left(_)), map(fb)(Right(_))) | |
} | |
implicit val optionUnionMonoidal: UnionMonoidal[Option] = new UnionMonoidal[Option] { | |
def union[A, B](fa: Option[A], fb: Option[B]): Option[A | B] = fa.orElse(fb) | |
def empty[A]: Option[A] = Option.empty | |
def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa.map(f) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment