为什么Haskell在读取Num时默认为读取Int? [英] Why does Haskell appear to default to reading Int when reading Num?

查看:118
本文介绍了为什么Haskell在读取Num时默认为读取Int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  foo ::(Num a)=> a  - > a 
foo x = x + x

main = do
print(foo(read7))

,因为不可能根据代码完全推断出类型(读7)。但是GHC(6.12.3)认为是不正确的,并打印出14个。

如果7更改为7.2,则代码将失败并显示no parse。这里发生了什么? Haskell如何决定使用哪个Read实例?

解决方案

这是由Haskell的 Num 类的违约规则。如果您添加了

  default(Double,Integer)

到文件顶部,那么你会得到以下结果:

 <$ c $打印14.0
print(foo(读取7.2)) - 打印14.2
打印(foo(读取7)) / code>

简而言之,违约规则是尝试尝试做正确的事情,并在遇到编译错误时你的程序中有一个模棱两可的类型。不幸的是,在这种情况下,它会为运行时错误导致编译时错误。



您可以禁用默认设置,如下所示:

  default()

这会迫使您明确通过类型注释来消除这些术语的类型:

  print(foo(read7:: Int))


I didn't expect the following code to work:

foo :: (Num a) => a -> a
foo x = x + x

main = do
    print (foo (read "7"))

because it is not possible to fully infer the type of (read "7") based on the code. But GHC (6.12.3) thinks otherwise and prints 14.

If "7" is changed to "7.2", the code fails with "no parse". What's going on here? how is Haskell deciding which instance of Read to use?

解决方案

This is caused by Haskell's defaulting rules for the Num class. If you added

default (Double, Integer)

to the top of your file, then you'd get the following results:

main = do
  print (foo (read "7")) -- prints "14.0"
  print (foo (read "7.2")) -- prints "14.2"

In a nutshell, defaulting rules are an attempt to "try to do the right thing" and save you from a compile error when you have an ambiguous type in your program. Unfortunately in this case it trades a compile-time error for a runtime error.

You can disable defaulting like so:

default ()

which will force you to explicitly disambiguate the types of such terms via type annotations:

print (foo (read "7" :: Int))

这篇关于为什么Haskell在读取Num时默认为读取Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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