简体   繁体   中英

Specialize class instance in PureScript

Say I have the following type:

newtype T1 a = T1 a

I can make a Show instance for it:

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 . 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:

> 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM