Section: 12 Typing Pitfalls

第 12 节 类型推断的陷阱

Section: 12.1 Let-Bound Polymorphism

第 12.1 节 let 绑定的多态

-- f g = (g 'a',g [])    -- This won't typecheck.

Section: 12.2 Overloaded Numerals

第 12.2 节 重载的数字字面量

Overloaded numerics were covered previously - here is one more example. sum is a prelude function which sums the elements of a list.

重载数值之前已经讲过——这里再给一个例子。sum 是 Prelude 中的函数,

对列表的元素求和。

average :: (Fractional a) => [a] -> a
average xs   = sum xs / fromIntegral (length xs)
e1 :: Float   -- Note that e1 would default to Double instead of Integer -
              -- this is due to the Fractional context.
e1 = average [1,2,3]

Section: 12.3 The Monomorphism Restriction

第 12.3 节 单态性限制

The monomorphism restriction is usually encountered when functions are defined without parameters. If you remove the signature for sum' the monomorphism restriction will apply. Hugs (at present) incorrectly defaults the type of sum' to Integer -> Integer without the type signature. If either of sumInt or sumFloat are present, these would determine the overloading. If both are present and sum' has no signature there is an error.

单态性限制通常在函数定义没有参数时遇到。如果你去掉 sum' 的签名,

单态性限制就会生效。Hugs(目前)在没有类型签名时,会错误地把 sum'

的类型默认为 Integer -> Integer。如果 sumInt 或 sumFloat 二者之一

存在,它们就能决定重载的选择。如果两者都存在而 sum' 没有签名,

就会报错。

sum' :: (Num a) => [a] -> a
sum' = foldl (+) 0         -- foldl reduces a list with a binary function
                           -- 0 is the initial value.
sumInt :: Int
sumInt = sum' [1,2,3]
sumFloat :: Float
sumFloat = sum' [1,2,3]

If you use overloaded constants you also may encounter monomorphism:

如果使用重载常量,你也可能遇到单态化:

x :: Num a => a
x = 1    -- The type of x is Num a => a
y :: Int
y = x            -- Uses x as an Int
z :: Integer
z = x          -- Uses x as an Integer.  A monomorphism will occur of the
               -- signature for x is removed.