如果存在(Show a),则返回`show a`;否则,如果(Typeable a),则返回其类型表示 [英] Return `show a` if (Show a) exists, otherwise its type representation if (Typeable a)

查看:130
本文介绍了如果存在(Show a),则返回`show a`;否则,如果(Typeable a),则返回其类型表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写

class Described a where
  describe :: a -> String

instance {-# OVERLAPPING #-} (Show a) => Described a where
  describe = show

instance {-# OVERLAPPABLE #-} (Typeable a) => Described a where
  describe = show . typeOf

这将无效,因为每个实例的右侧相同.我认为可以通过查看 https://wiki.haskell.org/GHC/AdvancedOverlap ,但似乎我需要为许多现有类型定义实例,以使这些解决方案中的任何一种都起作用.最好的解决方案是什么?

This won't work because the right hand side of each instance is the same. I thought would be solved by having a look at https://wiki.haskell.org/GHC/AdvancedOverlap but it seems that I need to define instances for many existing types to make any of these solutions work. What would be the best solution here?

推荐答案

指导实例选择的标准技巧是创建一个新类型.所以:

The standard trick for guiding instance selection is to make a new type. So:

newtype DescribeViaTypeable a = DVT a
newtype DescribeViaShow     a = DVS a

instance Show     a => Described (DescribeViaShow     a) where describe (DVS x) = show x
instance Typeable a => Described (DescribeViaTypeable a) where describe (DVT x) = show (typeOf x)

现在,调用者可以选择自己喜欢的描述类型(如果两者都可用),并且数据类型可以明确表示他们希望对其字段可用的描述类型,从而消除任何魔力.

Now callers may choose which kind of description they like if both are available, and data types can be explicit about which kind of description they expect to be available for their fields, eliminating any magic.

这篇关于如果存在(Show a),则返回`show a`;否则,如果(Typeable a),则返回其类型表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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