我想写
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),则返回其类型表示
发布评论