Haskell analog instance?

I'm new to Haskell, so my question is probably stupid.

I need a function

show2 :: (Show a) => a -> String

which will return show afor anyone a, but aif a is itself String. How to implement it?

PS great if this function is already implemented somewhere, but I still want to see an example implementation.

+4
source share
3 answers

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 -XUndecidableInstancesto compile and use it.

*Main> show2 "abc"
"abc"
*Main> show2 3
"3"
+4
source

You can use castfromData.Typeable

show2 :: (Typeable a, Show a) => a -> String
show2 s = maybe (show s) id ms
  where ms = cast s :: Maybe String
+5
source

, Haskell, instanceof. Haskell ​​ , Haskell : , .

, Haskell-Lee, , , Haskell , , ( , Java, , - !).

, - instanceof . - . ( ):

: , , : , , , , instanceof, , .

Haskell:

  • , , .
  • , , .

, - :

class ToString a where
    toString :: a -> String

instance ToString String where
    toString str = str

instance ToString Integer where
    toString i = show i

-- ...
+4

All Articles