不相关函数之间Haskell中类型错误的向后传播

时间:2015-03-05 20:15:32

标签: haskell

我正在为一个演示制作一个简单的程序,其中一个函数定义成功编译(并运行),但是添加一个后面的函数定义会在上一个函数中创建一个错误。

这一切都很好:

factors n = [ x | x <- [2..s], mod n x ==0]
      where s = floor $ sqrt(fromIntegral n)

然后我添加了一些错误:

-- this is wrong - but why cause earlier errors?
-- getDigs ns = map digitToInt $ map show ns   -- Bad
-- getDigs ns = map digitToInt $     show ns   -- Good
getDigs :: Int -> [Int]
getDigs ns = map digitToInt $ map show ns

它导致之前定义错误,之前已正确编译。我得到的错误是:

preTest.hs:8:17:
    Could not deduce (RealFrac s0) arising from a use of `floor'
    from the context (Integral t)
      bound by the inferred type of factors :: Integral t => t -> [t]
      at preTest.hs:(7,1)-(8,44)
    The type variable `s0' is ambiguous
    Note: there are several potential instances:
      instance RealFrac Double -- Defined in `GHC.Float'
      instance RealFrac Float -- Defined in `GHC.Float'
      instance Integral a => RealFrac (GHC.Real.Ratio a)
        -- Defined in `GHC.Real'
    In the expression: floor
    In the expression: floor $ sqrt (fromIntegral n)
    In an equation for `s': s = floor $ sqrt (fromIntegral n)

如果我显式键入第一个函数( factors :: Int - &gt; [Int] ),那么编译器会在第二个函数中正确地找到错误。推断类型是:

factors :: Integral t => t -> [t]

我没有看到这两个定义之间有任何共享,为什么要进行这种互动呢?

(GHCi 7.8.3)

0 个答案:

没有答案