Search code examples
haskellghctypeclassinferenceunification

GHC do not resolve correctly constraint in typeclass methods (ghc bug / limitation ?)


GHC do not resolve / propagate constraint in the default implementation of some of my class members. The behaviour is really strange and it seems to me like it's a bug.

Can someone help me / explain to me what's wrong ?

  1. How can I tell GHC to unify the a from the class declaration and the a from the class method so the definition is not ambiguous
  2. Is there something I don't understand ?

code:

module Foo where
import Data.Proxy

data Stuff a = Stuff
  {content :: String}

class HasStuff a where
  stuff :: Stuff a

  -- This works
  useStuffOK :: Proxy a -> (Stuff a)
  useStuffOK _ = (stuff)

  -- those don't work, 
  -- (but I think ghc has all the information necessary to figure it out)
  useStuffBAD :: Proxy a -> (Stuff a, String)
  useStuffBAD _ = (stuff, content (stuff :: Stuff a))
  -- Could not deduce (HasStuff a1) arising from a use of ‘stuff’
  -- from the context (HasStuff a)
  --   bound by the class declaration for ‘HasStuff’
  --   at Test.hs:(7,1)-(17,45)

  useStuffBAD2 :: Proxy a -> String
  useStuffBAD2 _ = content (stuff :: Stuff a)
  -- Could not deduce (HasStuff a1) arising from a use of ‘stuff’
  -- from the context (HasStuff a)
  --   bound by the class declaration for ‘HasStuff’
  --   at Test.hs:(7,1)-(17,45)

instance HasStuff Int where
  stuff = Stuff "ok"

-- inference works here
x :: Stuff Int
x = stuff

-- works here too
x :: String
x = content (stuff :: Stuff Int)

Thank you


Solution

  • as @epsilonhalbe and @user2407038 pointed out, I was missing ScopedTypeVariables extension