No instance arising [GHC-39999]

This error happens when an expression in the code has a type constraint (e.g. Eq a => a -> a) requiring an instance of a type class but GHC can‘t find it. This most commonly happens for two reasons: Either the type is too polymorphic (i.e. general) e.g. forall a. a and there is no type signature declaring that the type should have the instance. Or the type is specific e.g. Bool, but there is no instance for the desired type class defined for this type.

Examples

A usage of (==) on a data type which doesn‘t have an instance for Eq.

Error message

Main.hs:4:15: error: [GHC-39999]
    • No instance for (Eq Foo) arising from a use of ‘==’
    • In the expression: foo == A
      In an equation for ‘isA’: isA foo = foo == A
  |
4 | isA foo = foo == A
  |               ^^

Explanation

The operator == is only defined on types which have an instance for the Eq type class. The data type Foo does not have an instance. So GHC doesn‘t know how to compare values of Foo. To make this example compile we can create an Eq instance by using a derive statement.

Main.hs
Before
data Foo = A | B

isA :: Foo -> Bool
isA foo = foo == A
After
data Foo = A | B deriving Eq

isA :: Foo -> Bool
isA foo = foo == A
A usage of `+` on a too polymorphic variable.

Error message

Main.hs:2:11: error: [GHC-39999]
    • No instance for (Num a) arising from a use of ‘+’
      Possible fix:
        add (Num a) to the context of
          the type signature for:
            add :: forall a. a -> a -> a
    • In the expression: x + y
      In an equation for ‘add’: add x y = x + y
  |
2 | add x y = x + y
  |           ^

Explanation

The operator + is only defined on types which have an instance of the Num type class. If the function has the signature a -> a -> a someone could e.g. pass in a String for a and GHC wouldn‘t know how to add two Strings. Too fix it, like the compiler suggests, we add the Num a => constraint to the type signature to make sure that all users of add provide a suitable Num instance.

Main.hs
Before
add :: a -> a -> a
add x y = x + y
After
add :: Num a => a -> a -> a
add x y = x + y