2011-10-02 36 views
2
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甚至在這裏涉及?

回答

5

問題是,有兩個 monoids定義爲數字。一個加法,一個加乘法。這些實現爲新類型SumProduct的實例,您必須指定您想要的那個,因爲對於普通數字類型沒有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 

這通常會導致不明確的類型錯誤所有的地方,如果不是因爲類型違約,這使編譯器去通過一組默認類型(通常爲IntegerDouble),然後選擇適合的第一個。由於IntegerDouble都沒有Monoid實例,因此鍵入默認值失敗,並且您將得到不明確的類型錯誤。

你也有可能使用列表monoid,因爲從問題中不清楚你期待的結果。

*Main> times 5 [5] 
[5,5,5,5,5] 
+0

謝謝,哈馬爾。我對代碼做了一些更改,現在我得到一個新的錯誤:http://paste.pocoo.org/show/486225/。 (這實際上應該是一個單獨的問題,如果您要求,我會創建一個新線程。) – missingfaktor

+1

@missingfaktor:該實例需要「UndecidableInstances」擴展名。 – hammar

+0

我的確在等待'Int'的Monoid實例,但不知道沒有一個實例。 – missingfaktor

相關問題