Skip to content

Instantly share code, notes, and snippets.

@wheaties
Last active January 5, 2017 16:25
Show Gist options
  • Select an option

  • Save wheaties/e59fde66b2b69bc409425be1ecd10094 to your computer and use it in GitHub Desktop.

Select an option

Save wheaties/e59fde66b2b69bc409425be1ecd10094 to your computer and use it in GitHub Desktop.
Implicit existence based Either
//Either based on the existence of a typeclass.
sealed trait Exists[TC[_], N, Y]{
def apply(no: N, yes: Y): Either[N, Y]
}
object Exists extends LowPriorityExists{
def apply[TC[_]] = new{
def apply[N, Y](n: N, y: Y)(implicit exists: Exists[TC, N, Y]) = exists(n, y)
}
implicit def yes[TC[_], N, Y](implicit tc: TC[Y]) = new Exists[TC, N, Y]{
def apply(no: N, yes: Y): Either[N, Y] = Right(yes)
}
}
trait LowPriorityExists{
implicit def no[TC[_], N, Y] = new Exists[TC, N, Y]{
def apply(no: No, yes: Y): Either[N, Y] = Left(no)
}
}
Exists[Monoid](that :: Nil, that).fold(
other :: _,
implicitly[Monoid[That]].append(_, other)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment