一元限制是什么?我很困惑Haskell编译器有时如何推断出不像我预期的那样多态的类型,例如在使用无点定义时。问题似乎是“单形限制”,默认情况下,这是在较早版本的编译器上设置的。考虑以下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我没有获得任何错误,可执行文件的输出如下: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]如预期的那样。但是,如果我试图将其更改为: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产生以下错误: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不是多态的,需要Int争吵?唯一提到Int在应用程序的plus如果定义显然是多态的,这又有什么关系呢?为什么ghc突然觉得sort需要Num Char举个例子?编译时会出现以下错误:TestMono.hs:10:15:
No instance for (Ord a0) arising from a use of ‘compare’
The type variable ‘a0’ 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能够使用多态类型Ord a => [a] -> [a]为sort?为什么ghc治疗plus和plus'不一样?plus应该具有多态类型Num a => a -> a -> a我看不出这和sort但只有sort引发错误。
添加回答
举报
0/150
提交
取消