首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有HashMap的不明确类型变量

带有HashMap的不明确类型变量
EN

Stack Overflow用户
提问于 2012-12-07 04:32:14
回答 1查看 213关注 0票数 4

我最近开始玩haskell,在使用HashMap时遇到了一个问题,可以通过这个玩具示例来说明:

代码语言:javascript
复制
import Data.HashMap as HashMap

foo = HashMap.insert 42 53 HashMap.empty

以下是我在解释器中加载或编译文件时得到的错误:

代码语言:javascript
复制
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>

但是,如果我直接在解释器中定义完全相同的函数,我不会得到任何错误:

代码语言:javascript
复制
Prelude List HashMap> let foo = HashMap.insert 42 53 HashMap.empty
Prelude List HashMap>

有谁对此有什么线索吗?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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在以下情况下是可缺省的:

  • v仅以C v形式的约束出现,其中C是类,
  • 这些类中至少有一个是数值类(即Num或Num的子类)和
  • 所有这些类都是在前缀或标准库

中定义的

相关规则是,根据报告,只有在标准库中定义了所有涉及的类时,才会执行默认设置,但键上的Hashable约束涉及不满足该要求的类。

因此,编译器拒绝它,因为它不能解析由键产生的不明确的类型变量,而ghci将其缺省为Integer,因为如果涉及其他类,ghci也将缺省。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13752014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档