[英]Specialize class instance in PureScript
Say I have the following type: 说我有以下类型:
newtype T1 a = T1 a
I can make a Show
instance for it: 我可以为其创建一个
Show
实例:
instance showT1Generic :: Show a => Show (T1 a) where
show (T1 a) = "generic: " <> show a
However, let's say I want to do something special for types T1 Int
. 但是,假设我想对
T1 Int
类型做一些特殊的事情。 I tried doing this: 我尝试这样做:
instance showT1Int :: Show (T1 Int) where
show (T1 a) = "int: " <> show a
and it compiles, however running in psci
doesn't work as expected: 并且可以编译,但是在
psci
中运行无法按预期运行:
> T1 'a'
generic: 'a'
> T1 1
generic: 1
Am I doing this wrong? 我做错了吗?
Defining both those instances will raise an OverlappingInstances
warning, for the reason you're finding here - it can make the instance that is chosen unpredictable. 定义这两个实例将引发
OverlappingInstances
警告,这是您在这里发现的原因-它会使选定的实例不可预测。
I think if you flip the order of the instance definitions this will work, but it's not really recommended to ignore the OverlappingInstances
warning. 我认为,如果您翻转实例定义的顺序,则可以使用,但实际上不建议您忽略
OverlappingInstances
警告。
You can't really do what you're trying to do here - you could alter the behaviour of an instance with a newtype, but specialising instances for some concrete types and having a generic fallback is always going to result in overlapping instances as it stands. 您实际上不能做您想在这里做的事情-您可以使用新类型更改实例的行为,但是专门针对某些具体类型的实例并具有通用后备总是会导致实例重叠。 Maybe if we introduce instance chains this will become possible, but until then you're better off using monomorphic functions for this kind of thing.
也许如果我们引入实例链,这将成为可能,但是在那之前,最好还是使用单态函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.