首先,這隻適用於ghci
。如果你嘗試編譯此程序ghc
你會得到一個錯誤類型:
Test.hs:3:19:
Ambiguous type variable `a0' in the constraint:
(Show a0) arising from a use of `show'
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `($)', namely `show []'
In the expression: putStrLn $ show []
In an equation for `main': main = putStrLn $ show []
添加型簽名使錯誤消失:
module Main where
main = putStrLn $ show ([]::[Int])
但爲什麼它在ghci
工作?答案是extended type defaultingghci
:a
的類型默認爲()
(單位類型)。
這種行爲的動機是,用戶總是在解釋器中工作時指定類型有點令人厭煩。作爲維圖斯注意到,評論,運行ghci
與-Wall
(或添加:set -Wall
您~/.ghci
)可以更容易地發現瀆職:
<interactive>:2:12:
Warning: Defaulting the following constraint(s) to type `()'
(Show a0) arising from a use of `show'
In the second argument of `($)', namely `show []'
In a stmt of an interactive GHCi command: it <- putStrLn $ show []
'purStrLn $顯示[1]'仍然默認爲一個類型, '[1] ::(Num n)=> [n]' – amindfv
確實如此,但在這種情況下有默認值。 – Totoro
請注意,當類型變量不受約束時(例如, 'length []',參見:http://stackoverflow.com/q/7076517。 – hammar