Skip to content

Instantly share code, notes, and snippets.

@nuttycom
Last active December 23, 2015 20:39
Show Gist options
  • Save nuttycom/6690987 to your computer and use it in GitHub Desktop.
Save nuttycom/6690987 to your computer and use it in GitHub Desktop.
trait Functor {
type M <: { type T }
def fmap[A, B](fa: M { type T = A })(f: A => B): M { type T = B }
}
implicit class EitherRightFunctor extends Functor { self =>
type L
type M = Either { type A = self.L ; type T = B } //doesn't this specify a subtype of Either, rather than Either itself?
def fmap[A0, B0](fa: M { type A = self.L ; type B = A0 })(f: A0 => B0): Either { type A = self.L ; type B = B0 } =
fa match {
case Right(a) => Right(f(a))
case Left(l) => Left(l)
}
}
// current Scala
trait Functor[M[_]] {
def fmap[A, B](fa: M[A])(f: A => B): M[B]
}
implicit class EitherRightFunctor[L] extends Functor[({ type l[a] = Either[L, a] })#l] {
def fmap[A, B](fa: Either[L, A])(f: A => B): Either[L, B] =
fa match {
case Right(a) => Right(f(a))
case Left(l) => Left(l)
}
}
@nuttycom
Copy link
Author

Of course, if we had proper type-level lambdas, the "current Scala" version would be less noisy.

I think that the messiness of the former shows just how difficult it is to encode universal type constraints in terms of existential type constraints, which is really what we're trying to do here. The really ironic thing is that going the other direction, encoding existential types in terms of universals, is easy as https://gist.github.com/puffnfresh/6675849 demonstrates so nicely.

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