Ambiguous type variable with HashMap

I recently started playing with haskell, and I ran into a problem when using HashMap, which can be illustrated by the example of this toy:

import Data.HashMap as HashMap foo = HashMap.insert 42 53 HashMap.empty 

Here is the error I get when I upload a file to the interpreter or compile it:

 Prelude List HashMap> :load TypeError.hs [1 of 1] Compiling Main ( TypeError.hs, interpreted ) TypeError.hs:3:22: Ambiguous type variable `k0' in the constraints: (Num k0) arising from the literal `42' at TypeError.hs:3:22-23 (Ord k0) arising from a use of `insert' at TypeError.hs:3:7-20 (Data.Hashable.Hashable k0) arising from a use of `insert' at TypeError.hs:3:7-20 Possible cause: the monomorphism restriction applied to the following: foo :: Map k0 Integer (bound at TypeError.hs:3:1) Probable fix: give these definition(s) an explicit type signature or use -XNoMonomorphismRestriction In the first argument of `insert', namely `42' In the expression: insert 42 53 empty In an equation for `foo': foo = insert 42 53 empty Failed, modules loaded: none. Prelude List HashMap> 

However, if I define the same function directly in the interpreter, I get no error:

 Prelude List HashMap> let foo = HashMap.insert 42 53 HashMap.empty Prelude List HashMap> 

Does anyone know about this?

Thanks.

+4
source share
1 answer

The reason is that ghci uses extended default rules, while the compiler uses (default) the default rules specified in the language report :

Ambiguities are most often encountered in the Num class, therefore, Haskell provides another way to resolve them - with a default declaration: default (t1, ..., tn), where n โ‰ฅ 0, and each ti must be the type for which Num ti holds. In situations where an ambiguous type is found, a variable of an ambiguous type v does not work if:

  • v appears only in constraints of the form C v, where C is a class and
  • at least one of these classes is a number class (i.e. Num or a subclass of Num) and
  • all of these classes are defined in the prelude or standard library

The corresponding rule is that for a report by default it is executed only if all related classes are defined in the standard library, but the Hashable key restriction includes a class that does not meet this requirement.

Thus, the compiler rejects it because it cannot resolve an ambiguous type variable arising from the key, while ghci uses its Integer by default, since ghci also uses other classes by default.

+6
source

All Articles