Haskell:类型推断和函数组合

发布于 2024-08-02 23:23:19 字数 629 浏览 12 评论 0原文

这个问题的灵感来自于这个回答另一个问题,表明您可以使用定义为的函数从列表中删除每个出现的元素:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谎言月老 2024-08-09 23:23:19

为什么 Haskell 为函数推断出这样一个特定的类型?

GHCi 使用默认类型,从一组可能的类型中推断出更具体的类型。您可以通过禁用单态限制来轻松避免这种情况,

Prelude> :set -XNoMonomorphismRestriction
Prelude> let removeall = filter . (/=)
Prelude> :t removeall 
removeall :: (Eq a) => a -> [a] -> [a]

Why is Haskell inferring such a specific type for the function?

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,

Prelude> :set -XNoMonomorphismRestriction
Prelude> let removeall = filter . (/=)
Prelude> :t removeall 
removeall :: (Eq a) => a -> [a] -> [a]
与往事干杯 2024-08-09 23:23:19

还值得注意的是,如果您不为表达式分配名称,类型检查器似乎会避免类型默认:

Prelude> :t filter . (/=)
filter . (/=) :: (Eq a) => a -> [a] -> [a]

It is also worth noting that if you don't assign a name to the expression, typechecker seems to avoid type defaulting:

Prelude> :t filter . (/=)
filter . (/=) :: (Eq a) => a -> [a] -> [a]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文