haskell - 为什么在将现有函数与新名称相同分配时,Haskell 无法推断类型?
问题描述
我正在为一些 Haskell 的中缀运算符(特别是 +、-、*、/、:、<、<=、>、>=、==、/=)编写前缀名称。我将定义写入文件并将它们加载到 GHCi 中。起初我用两个参数编写了每个函数,比如
geq x y = x >= y
这适用于所有列出的运营商。然后我尝试通过自己分配函数来做同样的事情,比如
geq = (>=)
它适用于算术运算符和连接,但为比较运算符给出了以下错误:
test.hs:1:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘>=’
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 可以使用该定义?
解决方案
推荐阅读
- android - OpenGL ES - uv-scroll (GL_REPEAT) 在渲染第二个纹理时停止工作
- sql-server - 在 ROWS BETWEEN 子句的存储过程中使用变量
- python - 多类分类器神经网络问题
- php - laravel 编辑 index.php 后上传 HTTP ERROR 500
- mysql - MySql IN($list) 仅在出现在列表中时才匹配
- javascript - 如何确保在 Laravel 中不会两次加载脚本并向它们添加应用程序版本
- c++ - 由于没有运算符的 CString 连接 (?) 导致的 MemoryException
- javascript - 访问每个承诺中的 URL
- ms-access - 根据表单中的行输入过滤的列标题下拉列表
- freeradius - 如何知道我在 eap.conf 中使用了什么方法