为什么我在这里得到"模糊类型变量"错误?

mis*_*tor 2 haskell functional-programming

import Data.Monoid

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

main =
  print $ times 5 5
Run Code Online (Sandbox Code Playgroud)

此代码提供以下错误:

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
Run Code Online (Sandbox Code Playgroud)

为什么会出现此错误?Num甚至怎么参与这里?

ham*_*mar 5

问题是为数字定义了两个幺半群.一个有加法,一个有乘法.这些实现作为newtypes实例SumProduct,你必须指定要哪一个,因为有对普通的数值类型没有幺实例.

*Main> times 5 (Sum 5)
Sum {getSum = 25}
*Main> times 5 (Product 5)
Product {getProduct = 3125}
Run Code Online (Sandbox Code Playgroud)

Num提到因为5是多态值:

*Main> :t 5
5 :: Num a => a
Run Code Online (Sandbox Code Playgroud)

这通常会导致整个地方出现模糊类型错误,如果不是类型违约,这会导致编译器通过一组默认类型(通常IntegerDouble),并选择第一个适合的类型.由于既没有Integer,也不DoubleMonoid实例,请键入违约失败,你会得到不明确的错误类型.

也有可能你打算使用列表monoid,因为从问题中你不期望得到什么结果.

*Main> times 5 [5]
[5,5,5,5,5]
Run Code Online (Sandbox Code Playgroud)