首页 > 解决方案 > 为什么在将现有函数与新名称相同分配时,Haskell 无法推断类型?

问题描述

我正在为一些 Haskell 的中缀运算符(特别是 +、-、*、/、:、<、<=、>、>=、==、/=)编写前缀名称。我将定义写入文件并将它们加载到 GHCi 中。起初我用两个参数编写了每个函数,比如

geq x y = x >= y

这适用于所有列出的运营商。然后我尝试通过自己分配函数来做同样的事情,比如

geq = (>=)

它适用于算术运算符和连接,但为比较运算符给出了以下错误:

test.hs:1:1: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘&gt;=’
      prevents the constraint ‘(Ord a0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Ord Ordering -- Defined in ‘GHC.Classes’
        instance Ord Integer
          -- Defined in ‘integer-gmp-1.0.0.1:GHC.Integer.Type’
        instance Ord a => Ord (Maybe a) -- Defined in ‘GHC.Base’
        ...plus 22 others
        ...plus five instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • When instantiating ‘geq’, initially inferred to have
      this overly-general type:
        forall a. Ord a => a -> a -> Bool
      NB: This instantiation can be caused by the monomorphism restriction.
Failed, modules loaded: none.

向函数添加类型注释

geq :: Ord a => a -> a -> Bool

(我从 GHCi 中获取的:t (>=))解决了这个问题。有趣的是,如果我在交互式提示中这样做,GHCi 似乎可以接受被拒绝的定义,比如

let geq = (>=)

但是比较运算符如何使 Haskell 无法推断 的类型geq = (>=),这似乎甚至不需要任何推断?Haskell 使用什么算法进行类型推断,如果没有类型注释的 Haskell 无效,为什么 GHCi 可以使用该定义?

标签: haskelltypestype-inference

解决方案


推荐阅读