Reputation: 161
In Haskell, is there any way to declare function it behaves differently depending on whether the type of a argument is an instance of specific type class?
For example, can I define genericShow
in the following example?
-- If type `a` is an instance of `Show`.
genericShow :: Show a => a -> String
genericShow = show
-- If type `a` is not an instance of `Show`.
genericShow :: a -> String
genericShow _ = "(Cannot be shown)"
> genericShow 3
"3"
> genericShow const
"(Cannot be shown)"
Upvotes: 1
Views: 234
Reputation: 2806
No.
The closest you can get is to use Overlapping instances, with a catch-all instance for anything not having a more specific Show
instance.
instance {-# OVERLAPPABLE #-} Show a where
show _ = "(Cannot be shown)"
Overlapping instances come with lots of caveats: see topics like 'orphan instances', 'Incoherent instances'. That's particularly awkward with Prelude
classes like Show
, because there's likely to be lots of instances hidden away in libraries.
As @duplode says, there are many dangers. Almost certainly there's a better way to achieve whatever it is you think you want.
Upvotes: 1