一元限制是什么?
{-# 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