Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell instanceof analogue?

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.

like image 424
Prof. Legolasov Avatar asked Mar 26 '15 17:03

Prof. Legolasov


People also ask

What is the difference between Instanceof and isInstance?

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.

What can I use instead of Instanceof in Java?

Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".

What is Instanceof used for?

instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.


2 Answers

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
like image 82
Lee Avatar answered Sep 30 '22 05:09

Lee


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"
like image 30
n. 1.8e9-where's-my-share m. Avatar answered Sep 30 '22 04:09

n. 1.8e9-where's-my-share m.