模糊类型和重载数值操作的默认值 [英] Ambiguous Types, and Defaults for Overloaded Numeric Operations

查看:71
本文介绍了模糊类型和重载数值操作的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import Data.Dynamic

default(Integer,Double)

a :: Num a => a
a = 5

-- show :: Show a => a -> String
-- toDyn :: Typeable a => a -> Dynamic

main :: IO ()
-- main = print $ show a -- *** THIS LINE WORKS WELL
main = print $ toDyn a   -- *** THIS LINE LEADS TO AN AMBIGUOUS TYPE ERROR

我不明白为什么第一个主要"版本有效,而不是第二个为什么. 有没有人可以帮助我? 预先感谢您的答复.

I don't understand why the first "main" version works, and not the second. Is there someone who can help me ? Thanks in advance for your reply.

推荐答案

来自 Haskell报告:

在发现模棱两可的类型的情况下,如果出现以下情况,则模棱两可的类型变量 v 是默认的:

  • v 仅出现在形式为 C v 的约束中,其中 C 是一个类,并且
  • 这些类中的至少一个是数字类(即NumNum)的子类,并且
  • 所有这些类均在Prelude或标准库中定义
  • v appears only in constraints of the form C v, where C is a class, and
  • at least one of these classes is a numeric class, (that is, Num or a subclass of Num), and
  • all of these classes are defined in the Prelude or a standard library

您的示例失败了,因为与Show不同,Typeable不是第三点中指定的类之一,因此不执行默认设置.

Your example fails because unlike Show, Typeable is not one of the classes specified in the third point, so no defaulting is performed.

这篇关于模糊类型和重载数值操作的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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