我最近开始玩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>有谁对此有什么线索吗?
谢谢。
发布于 2012-12-07 04:42:09
原因是ghci使用扩展的缺省规则,而编译器(缺省情况下)使用defaulting rules specified in the language report
类Num中的歧义是最常见的,因此Haskell提供了另一种方法来解决它们-使用默认声明: default (t1,…,tn),其中n≥0,并且每个ti必须是Num ti保持的类型。在发现不明确类型的情况下,不明确类型变量v在以下情况下是可缺省的:
中定义的
相关规则是,根据报告,只有在标准库中定义了所有涉及的类时,才会执行默认设置,但键上的Hashable约束涉及不满足该要求的类。
因此,编译器拒绝它,因为它不能解析由键产生的不明确的类型变量,而ghci将其缺省为Integer,因为如果涉及其他类,ghci也将缺省。
https://stackoverflow.com/questions/13752014
复制相似问题