如果存在(Show a),则返回`show a`;否则,如果(Typeable a),则返回其类型表示

编程入门 行业动态 更新时间:2024-10-28 12:23:02
本文介绍了如果存在(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

这将无效,因为每个实例的右侧相同.我认为可以通过查看 wiki.haskell/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 wiki.haskell/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),则返回其类型表示

本文发布于:2023-10-18 03:01:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   Show   show   Typeable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!