一元限制是什么?我很困惑Haskell編譯器有時如何推斷出不像我預(yù)期的那樣多態(tài)的類型,例如在使用無點定義時。問題似乎是“單形限制”,默認情況下,這是在較早版本的編譯器上設(shè)置的??紤]以下Haskell程序:{-# LANGUAGE MonomorphismRestriction #-}import Data.List(sortBy)plus = (+)plus' x = (+ x)sort = sortBy compare
main = do
print $ plus' 1.0 2.0
print $ plus 1.0 2.0
print $ sort [3, 1, 2]如果我用ghc我沒有獲得任何錯誤,可執(zhí)行文件的輸出如下:3.03.0[1,2,3]如果我更改main尸體:main = do
print $ plus' 1.0 2.0
print $ plus (1 :: Int) 2
print $ sort [3, 1, 2]我沒有編譯時錯誤,輸出變成:3.03[1,2,3]如預(yù)期的那樣。但是,如果我試圖將其更改為:main = do
print $ plus' 1.0 2.0
print $ plus (1 :: Int) 2
print $ plus 1.0 2.0
print $ sort [3, 1, 2]我得到一個類型錯誤:test.hs:13:16:
No instance for (Fractional Int) arising from the literal ‘1.0’
In the first argument of ‘plus’, namely ‘1.0’
In the second argument of ‘($)’, namely ‘plus 1.0 2.0’
In a stmt of a 'do' block: print $ plus 1.0 2.0產(chǎn)生以下錯誤:test.hs:14:17:
No instance for (Num Char) arising from the literal ‘3’
In the expression: 3
In the first argument of ‘sort’, namely ‘[3, 1, 2]’
In the second argument of ‘($)’, namely ‘sort [3, 1, 2]’為什么ghc突然覺得plus不是多態(tài)的,需要Int爭吵?唯一提到Int在應(yīng)用程序的plus如果定義顯然是多態(tài)的,這又有什么關(guān)系呢?為什么ghc突然覺得sort需要Num Char舉個例子?編譯時會出現(xiàn)以下錯誤:TestMono.hs:10:15:
No instance for (Ord a0) arising from a use of ‘compare’
The type variable ‘a(chǎn)0’ is ambiguous
Relevant bindings include
sort :: [a0] -> [a0] (bound at TestMono.hs:10:1)
Note: there are several potential instances:
instance Integral a => Ord (GHC.Real.Ratio a)
-- Defined in ‘GHC.Real’
instance Ord () -- Defined in ‘GHC.Classes’
instance (Ord a, Ord b) => Ord (a, b) -- Defined in ‘GHC.Classes’
...plus 23 others
In the first argument of ‘sortBy’, namely ‘compare’
In the expression: sortBy compare
In an equation for ‘sort’: sort = sortBy compare為什么ghc能夠使用多態(tài)類型Ord a => [a] -> [a]為sort?為什么ghc治療plus和plus'不一樣?plus應(yīng)該具有多態(tài)類型Num a => a -> a -> a我看不出這和sort但只有sort引發(fā)錯誤。
一元限制是什么?
慕標琳琳
2019-06-03 17:21:21