输入奥秘。为什么这个代码编译? [英] Type mysteries. Why does this code compile?

查看:80
本文介绍了输入奥秘。为什么这个代码编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码无法编译:

  default()

f :: RealFloat a => ; a
f = 1.0

g :: RealFloat a => a
g = 1.0

h :: Bool
h = f < g - 错误。暧昧。

这是预料之中的,因为它不明确。这两种可能性是 Float Double ,编译器不知道哪个< 选择。



然而,这段代码并不会编译:

  default()

f :: RealFloat a => a
f = 1.0

g :: RealFloat a => a
g = 1.0

h :: RealFloat a => a
h = f + g - 为什么编译?

为什么?为什么Haskell在这里遇到困惑,与上面的例子类似,需要选择 + (for Float c $ c> h 也是具有多态类型。因此,使用 + 的类型不是不明确的;它只是还没有被选中。



使用 将决定选择哪种类型的 + (并且不同的使用地点可以做出不同的选择)。 h 的用户可以要求它提供他们所需的任何 RealFloat 类型; f g 也可以提供任何 RealFloat 类型,所以 h 只会询问他们的用户所要求的类型。


This code does not compile:

default ()

f :: RealFloat a => a
f = 1.0

g :: RealFloat a => a
g = 1.0

h :: Bool
h = f < g --Error. Ambiguous.

This is expected because it's ambiguous. The two possibilities are Float and Double and the compiler doesn't know which < to pick.

However, this code does compile:

default ()

f :: RealFloat a => a
f = 1.0

g :: RealFloat a => a
g = 1.0

h :: RealFloat a => a
h = f + g --Why does this compile?

Why? Why isn't Haskell confused here, in a similar manner as in the example above, about which + to pick (for Float or Double)?

解决方案

In your second example h also has a polymorphic type. So the type at which + is used isn't ambiguous; it just hasn't been chosen yet.

The context where h is used will determine which type's + is chosen (and different use-sites can make different choices). The user of h can ask it to provide any RealFloat type they please; f and g can also provide any RealFloat type, so h will just ask them for exactly the type its user is asking for.

这篇关于输入奥秘。为什么这个代码编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆