Haskell:类型推断和函数组合
这个问题的灵感来自于这个回答另一个问题,表明您可以使用定义为的函数从列表中删除每个出现的元素:
removeall = filter . (/=)
用铅笔和纸从 < 类型中计算出来code>filter、(/=)
和 (.)
,该函数的类型
removeall :: (Eq a) => a -> [a] -> [a]
正是您根据其约定所期望的类型。然而,对于 GHCi 6.6,
gchi> :t removeall
removeall :: Integer -> [Integer] -> [Integer]
除非我明确指定类型(在这种情况下它工作正常),否则我会得到。为什么 Haskell 为函数推断出这样一个特定的类型?
This question was inspired by this answer to another question, indicating that you can remove every occurrence of an element from a list using a function defined as:
removeall = filter . (/=)
Working it out with pencil and paper from the types of filter
, (/=)
and (.)
, the function has a type of
removeall :: (Eq a) => a -> [a] -> [a]
which is exactly what you'd expect based on its contract. However, with GHCi 6.6, I get
gchi> :t removeall
removeall :: Integer -> [Integer] -> [Integer]
unless I specify the type explicitly (in which case it works fine). Why is Haskell inferring such a specific type for the function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
GHCi 使用默认类型,从一组可能的类型中推断出更具体的类型。您可以通过禁用单态限制来轻松避免这种情况,
GHCi is using type defaulting, to infer a more specific type from a set of possibles. You can avoid this easily by disabling the monomorphism restriction,
还值得注意的是,如果您不为表达式分配名称,类型检查器似乎会避免类型默认:
It is also worth noting that if you don't assign a name to the expression, typechecker seems to avoid type defaulting: