[Haskell-cafe] Trouble with non-exhaustive patterns

Chaddaï Fouché chaddai.fouche at gmail.com
Mon Jul 21 07:46:49 EDT 2008

2008/7/21 Fernando Rodriguez <frr149 at easyjob.net>:
> Suddenly, the function stoped working with a rather cryptic (for a newbie at
> least) error message:
> *Temp> final [4,5]
> <interactive>:1:9:
>   No instance for (Num [a])
>     arising from the literal `5' at <interactive>:1:9
>   Possible fix: add an instance declaration for (Num [a])
>   In the expr*Temp> ession: 5
>   In the first argument of `final', namely `[4, 5]'
>   In the expression: final [4, 5]
> What have I done so wrong?

As Janis said final [] = [] conflicts with the signature you want for
final BUT the definition of final is still typeable, it just don't
have the type you think it have... and combined with the way Haskell
handle number literals you get this confusing error.

final's type is [[a]] -> [a] because final [] = [] imply that the
return type should be a list and thus (final [a] = a) imply that the
input list elements should themselves be lists (because a should be a
list since it is returned in this case)...

So final wants a list of list. All is well until now and if you try
for example :
> final [True, False]
you'll get a slightly better error message (maybe hard for newbies but
very understandable with a little bit of experience) :
    Couldn't match expected type `[a]' against inferred type `Bool'
    In the expression: True
    In the first argument of `final', namely `[True, False]'
    In the expression: final [True, False]

Now your error message is particularly nasty because all integer
literals like "5" are treated in the following fashion in Haskell :
they're implicitly translated to "fromInteger 5", fromInteger being a
function of the Num typeclass that for an instance Num a take an
Integer and translate it to the a type. This translation is normally
pretty obvious with some bound checking (for Int type) and simple
translation (to Double or Float) but you could in theory have some
pretty crazy instances of Num, [a] for example.
For example here Haskell complains that there are no Num instances for
the [a] type since that's what he want to translate the "5" into....

I hope you understood this explanation, even if it's a little bit
crazy and blury for now, just remember, most of the time if you have
an error like :
    No instance for (Num X)
       arising from the literal `5' at <interactive>:1:9
you can more or less translate it to :
    Couldn't match expected type `X' against inferred type `Integer'

(This is only true for the Num typeclass, since this is the only case
of polymorphic literals you'll meet for now).


More information about the Haskell-Cafe mailing list