Ensure all classes implicitly narrow/widen as appropriate
djspiewak opened this issue · 8 comments
For example, the Ask
classes should implicitly widen, while the Error
classes should implicitly narrow. The former is equivalent to making Kleisli
contravariant, while the latter is equivalent to making EitherT
covariant, but critically implicit encodings of this work even on polymorphic types. Quick example:
object ApplicativeAsk {
implicit def widen[F[_], A, B >: A](implicit F: ApplicativeAsk[F, A]): ApplicativeAsk[F, B] = ...
I've tried to get to this during last weeks stream, but I ran into a problem that I've minimized here:
trait Raise[F[_], E] {
def raise[A](e: E): F[A]
}
object Raise {
implicit def covariantRaise[F[_], E, E2 <: E](implicit F: Raise[F, E]): Raise[F, E2] =
new Raise[F, E2] {
def raise[A](e: E2): F[A] = F.raise(e)
}
}
sealed trait Err
case class FooErr(n: Int) extends Err
def foo[F[_]](implicit F: Raise[F, FooErr]) =
F.raise(FooErr(404))
def bar[F[_]](implicit F: Raise[F, Err]): F[Nothing] =
foo[F]
// diverging implicit expansion for type Raise[[_]F[_],FooErr]
// starting with method covariantRaise in object Raise
I would guess this is happening because subtyping is reflexive. I'm not sure how to avoid that without negative implicits, which cause bugs when composed with multi-stage inductive implicits (shims is forced to get around this using macros). We could also expose a tiny little utility macro which implements non-reflexive subtyping, unless such a thing already exists elsewhere.
Wonder if it'd just be easier to add the variance on the type class directly, especially given we want to be cross compiling with dotty ASAP
Worth a try! My guess is that you'll very quickly fall down into exciting Viral Variance Land, where the errors do not practice social distancing. Particularly with Dotty. But at the very least it's worth the experiment.
I can make Raise
contravariant pretty easily Raise[F[_], -E]
, but the problem is Handle
is invariant, which makes sense.
If I have a type hierarchy A <: B <: C
and an instance for Handle[F, B]
then there's really no way I could both raise and handle either A
or C
soundly. Am I missing something here?
Right, you would not be able to do both. But that's not really a problem. :-) Fortunately the compiler is going to do a decent job at checking soundness here. Handle
can be invariant while Raise
is contravariant without a problem. Having a Handle[F, C]
(in your example) certainly implies a Raise[F, A]
, but this won't be an issue for the original Handle
, and this is actually a rather useful thing in practice. Example:
def foo[F[_]](implicit h: Handle[F, Throwable]) = {
val eff = new RuntimeException().raise[F] // requires a Raise[F, RuntimeException]
eff.handle((t: Throwable) => ...)
}
There's no problem here.
That makes perfect sense, I didn't consider that Handle[F, C]
still implies a Raise[F, A]
, so that's neat, thanks! :)