import Data.Monoid
times :: Monoid a => Int -> a -> a
times i = mconcat . replicate i
main =
print $ times 5 5此代码显示以下错误:
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是如何参与其中的呢?
发布于 2011-10-03 05:32:42
问题是,有两个么半群定义的数字。一个是加法,另一个是乘法。这些是作为新类型Sum和Product的实例实现的,您必须指定所需的实例,因为没有用于普通数值类型的monoid实例。
*Main> times 5 (Sum 5)
Sum {getSum = 25}
*Main> times 5 (Product 5)
Product {getProduct = 3125}之所以提到Num,是因为5是一个多态值:
*Main> :t 5
5 :: Num a => a这通常会导致到处都是模棱两可的类型错误,如果不是类型缺省,这会导致编译器遍历一组缺省类型(通常是Integer和Double),并选择第一个合适的类型。由于Integer和Double都没有Monoid实例,因此默认类型失败,您会得到类型不明确的错误。
也有可能你打算使用列表么半群,因为从问题中不清楚你所期望的结果是什么。
*Main> times 5 [5]
[5,5,5,5,5]https://stackoverflow.com/questions/7629275
复制相似问题