为什么在Haskell中不推断多态值? [英] Why are polymorphic values not inferred in Haskell?

查看:95
本文介绍了为什么在Haskell中不推断多态值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数字文字有一个多态类型:

  * Main> :t 3 
3 ::(Num t)=> t

但是,如果我将一个变量绑定到这样一个文字上,多态性会丢失:

  x = 3 
...
* Main> :tx
x :: Integer

如果我定义一个函数,另一方面,它当然是多态的:

  fx = 3 
...
* Main> :t f
f ::(Num t1)=> t - > t1

我可以提供一个类型签名来确保 x 仍然是多态的:

  x :: Num a => a 
x = 3
...
* Main> :t x
x ::(Num a)=> a

但为什么这是必要的?为什么不推断多态类型?

解决方案

这是单态限制,它表示没有参数定义且没有显式类型注释的所有值应具有单形类型。 ghc和ghci可以使用 -XNoMonomorphismRestriction 禁用这个限制。 这个限制的原因是没有这个限制> long_calculation 42 会被评估两次,而大多数人可能会希望/只希望评估一次:

  longCalculation :: Num a => a  - > a 
longCalculation = ...

x = longCalculation 42

main =打印$ x + x


Numeric literals have a polymorphic type:

*Main> :t 3
3 :: (Num t) => t

But if I bind a variable to such a literal, the polymorphism is lost:

x = 3
...
*Main> :t x
x :: Integer

If I define a function, on the other hand, it is of course polymorphic:

f x = 3
...
*Main> :t f
f :: (Num t1) => t -> t1

I could provide a type signature to ensure the x remains polymorphic:

x :: Num a => a
x = 3
...
*Main> :t x
x :: (Num a) => a

But why is this necessary? Why isn't the polymorphic type inferred?

解决方案

It's the monomorphism restriction which says that all values, which are defined without parameters and don't have an explicit type annotation, should have a monomorphic type. This restriction can be disabled in ghc and ghci using -XNoMonomorphismRestriction.

The reason for the restriction is that without this restriction long_calculation 42 would be evaluated twice, while most people would probably expect/want it to only be evaluated once:

longCalculation :: Num a => a -> a
longCalculation = ...

x = longCalculation 42

main = print $ x + x

这篇关于为什么在Haskell中不推断多态值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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