GHCi 如何为类型变量选择名称?
使用交互式 GHC 解释器时,可以请求表达式的推断类型:
Prelude> :t map
map :: (a -> b) -> [a] -> [b]
它似乎从签名中获取类型变量的名称,因为 map
是 定义如
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
前奏中所示。这很有道理!我的问题是:当没有给出签名时,如何选择类型变量名称?
例如,
Prelude> :t map fst
map fst :: [(b, b1)] -> [b]
它选择了名称 b
和 b1
。很明显,必须进行重命名,但只需以 a
、b
、... 开头即可
map fst :: [(a, b)] -> [a]
,我发现这更具可读性。
When using the interactive GHC interpreter, it's possible to ask for the inferred type of an expression:
Prelude> :t map
map :: (a -> b) -> [a] -> [b]
It seems that it takes the names of the type variables from the signature since map
is defined as
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
in the Prelude. That makes a lot of sense! My question is: how are type variable names picked when there is no signature given?
An example would be
Prelude> :t map fst
map fst :: [(b, b1)] -> [b]
where it picked names b
and b1
. It's clear that renaming must take place, but simply starting with a
, b
, ... would have given
map fst :: [(a, b)] -> [a]
instead, which I find slightly more readable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我了解,ghci 按照推断类型的顺序选择名称。它使用您提到的命名方案来决定结果的类型名称,即
[b]
,因为这是map
定义中指定的类型名称。然后它决定作为map
的第一个参数的函数也应该返回b
类型的内容。因此,要命名的剩余类型变量是 fst 参数元组中第二个元素的类型变量,并且它再次查看 fst 的定义来决定哪个要使用的名称。
fst::(a, b) -> 的定义a
,因此b
将是此处的首选名称,但由于b
已被采用,因此它会附加一个1
,以便它变为b1
。我认为这个系统在您不处理任意类型的情况下具有优势,就像这里的情况一样。如果结果类型看起来像这样,例如:
... 它可以说比: ... 更具可读性
,因为您主要可以依赖
n#
表示数字类型,因为类定义Num
是class Num n where ...
。编辑:是的,我知道
castAdd
是不可能实现的,但这只是一个类型示例。As I understand it,
ghci
chooses names in the same order that it infers the types. It uses the naming scheme as you mentioned to decide the type name of the result, which is[b]
because that is the type name specified in the definition ofmap
. It then decides that the function that is the first parameter tomap
should return something of typeb
also.The remaining type variable to be named is thus the type variable for the second element in the argument tuple to
fst
, and again, it looks at the definition offst
to decide which name to use. The definition offst :: (a, b) -> a
, sob
would be the preferred name here, but sinceb
is already taken, it appends a1
so that it becomesb1
.I think that this system has advantages in situations where you don't deal with arbitrary types as is the case here. If the resulting type looks something like this, for example:
... it is arguably more readable than:
... because you can mostly rely on that
n#
signifies a numeric type, since the class definition forNum
isclass Num n where ...
.EDIT: Yes, I know that
castAdd
is impossible to implement, but it's just a type example.