首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我在这里得到“歧义类型变量”的错误?

为什么我在这里得到“歧义类型变量”的错误?
EN

Stack Overflow用户
提问于 2011-10-03 05:16:17
回答 1查看 164关注 0票数 2
代码语言:javascript
复制
import Data.Monoid

times :: Monoid a => Int -> a -> a
times i = mconcat . replicate i

main =
  print $ times 5 5

此代码显示以下错误:

代码语言:javascript
复制
Ambiguous type variable `a0' in the constraints:
  (Monoid a0) arising from a use of `times'
              at :7:11-15
  (Show a0) arising from a use of `print'
            at :7:3-7
  (Num a0) arising from the literal `5'
           at :7:19
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `($)', namely `times 5 5'
In the expression: print $ times 5 5
In an equation for `main': main = print $ times 5 5

为什么会出现这个错误?Num是如何参与其中的呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-03 05:32:42

问题是,有两个么半群定义的数字。一个是加法,另一个是乘法。这些是作为新类型SumProduct的实例实现的,您必须指定所需的实例,因为没有用于普通数值类型的monoid实例。

代码语言:javascript
复制
*Main> times 5 (Sum 5)
Sum {getSum = 25}
*Main> times 5 (Product 5)
Product {getProduct = 3125}

之所以提到Num,是因为5是一个多态值:

代码语言:javascript
复制
*Main> :t 5
5 :: Num a => a

这通常会导致到处都是模棱两可的类型错误,如果不是类型缺省,这会导致编译器遍历一组缺省类型(通常是IntegerDouble),并选择第一个合适的类型。由于IntegerDouble都没有Monoid实例,因此默认类型失败,您会得到类型不明确的错误。

也有可能你打算使用列表么半群,因为从问题中不清楚你所期望的结果是什么。

代码语言:javascript
复制
*Main> times 5 [5]
[5,5,5,5,5]
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7629275

复制
相关文章

相似问题

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