Can not deduce superclass

Viewed 257

In the following code, GHC can not find the Functor instance in the definition of Monoidal instance.

Why isn't GHC deducing that given the Applicative constraint is satisfied, then the Functor has to be somewhere already? (is there a name to this reasoning 'capability' ?)

import Prelude hiding (Applicative (..), Monad (..))

class Functor f => Applicative f where
  pure :: a -> f a
  (<*>) :: f (a -> b) -> f a -> f b

class Functor f => Monoidal f where
   unit::f ()
   (*) ::f a -> f b -> f (a,b)

instance Applicative f => Monoidal f where
  unit = pure ()
  a * b = undefined

I know could of course add an explicit Functor f constraint to Monoidal to not have the error, but my question is more on why instance resolution works that way

import Prelude hiding ((*), Applicative (..), Monad (..))

class Functor f => Applicative f where
  pure :: a -> f a
  (<*>) :: f (a -> b) -> f a -> f b

class Functor f => Monoidal f where
   unit::f ()
   (*) ::f a -> f b -> f (a,b)

instance (Applicative f, Functor f) => Monoidal f where
  unit = pure ()
  a * b = (pure (,) <*> a <*> b )

instance (Monoidal f, Functor f) => Applicative f where
  pure x = fmap (\_ -> x) unit
  mu <*> mx = fmap (\(f, x) -> f x) ((mu * mx) :: f (a -> b, a))
1 Answers

Looks like a bug to me. Here's a minimal file which shows the problem and doesn't rely on any shenanigans with renaming Prelude stuff or undefineds.

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
class A x
class A x => B x
class A x => C x
instance B x => C x

I recommend filing a bug on the GHC bug tracker with this file (or one very like it); the reasoning needed to discover that B x implies A x should be possible.

Related