我最近开始玩 haskell,在使用 HashMap 时遇到了一个问题,这个玩具示例可以说明这一点:
import Data.HashMap as HashMap
foo = HashMap.insert 42 53 HashMap.empty
这是我在解释器中加载文件或编译文件时遇到的错误:
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>
但是,如果我直接在解释器中定义完全相同的函数,则不会出现错误:
Prelude List HashMap> let foo = HashMap.insert 42 53 HashMap.empty
Prelude List HashMap>
有人对此有任何线索吗?
谢谢。