import Data.Monoid
times :: Monoid a => Int -> a -> a
times i = mconcat . replicate i
main =
print $ times 5 5
This code gives the following error:
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
Why does it give this error? How is Num even involved here?
The problem is that there are two monoids defined for numbers. One with addition, and one with multiplication. These are implemented as instances for the newtypes
SumandProduct, and you have to specify which one you want, as there are no monoid instances for plain numeric types.Numis mentioned because5is a polymorphic value:This would normally cause ambiguous type errors all over the place, if not for type defaulting, which causes the compiler to go through a set of default types (normally
IntegerandDouble), and choose the first one that fits. Since neitherIntegernorDoublehas aMonoidinstance, type defaulting fails, and you get the ambiguous type error.It’s also possible that you meant to use the list monoid, as it’s not clear from the question what result you were expecting.