I am new to Haskell, so my question is probably stupid.
I want a function
show2 :: (Show a) => a -> String
which would return show a
for any a
, but a
if a is itself String
.
How can I implement it?
P.S. it is great if this function is already implemented somewhere, but I still want to see an example of the implementation.
The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator.
Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".
instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.
You can use cast
from Data.Typeable
show2 :: (Typeable a, Show a) => a -> String
show2 s = maybe (show s) id ms
where ms = cast s :: Maybe String
You can do this with this piece of dirty and dangerous code:
class Showable a where
show2 :: a -> String
instance Showable String where
show2 = id
instance (Show a) => Showable a where
show2 = show
You need -XOverlappingInstances -XFlexibleInstances -XUndecidableInstances
to compile and use it.
*Main> show2 "abc"
"abc"
*Main> show2 3
"3"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With