0

How can I define an instance for showing (String, String) structure

instance Show (String, String) where
show (a, b) = show a ++ show b

Thanks!

yonutix
  • 1,964
  • 1
  • 22
  • 51

2 Answers2

2

If you'd used proper indentation, and switched on the altogether harmless -XFlexibleInstances

{-# LANGUAGE FlexibleInstances #-}
instance Show (String, String) where
  show (a, b) = show a ++ show b

then this instance would, in itself, work (you need to switch on -XFlexibleInstances). However, it won't compile because a strictly more general instance

instance (Show a, Show b) => Show (a, b) where
  show (a, b) = "(" ++ show a ++ "," ++ show b ++ ")"

is already defined in the prelude. If you're determined to override that one then you also need to switch on -XOverlappingInstances. But this one is not so harmless; in fact it's evil: overlapping instances can lead to all kinds of trouble, and for your specific definition the instance also doesn't comply with the requirement that read . show ≡ id.

Community
  • 1
  • 1
leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
2

The short answer is that you can't without a bunch of language extensions that really are better suited to other tasks.

There is already an instance for (Show a, Show b) => Show (a, b), meaning that defining it for (String, String) would overlap with the already existing one. A better choice would be to write your own showStrTuple as

showStrTuple :: (String, String) -> String
showStrTuple (a, b) = show a ++ show b

Alternatively, if you really want to use show on it, make a newtype (which are designed for defining new typeclasses that would otherwise conflict with existing ones):

newtype StrTuple = StrTuple { unStrTuple :: (String, String) } deriving (Eq)

instance Show StrTuple where
    show (StrTuple (a, b)) = show a ++ show b

Then you just construct it with

show $ StrTuple ("hello", "world")
bheklilr
  • 53,530
  • 6
  • 107
  • 163
  • You are right, however, I asked this to use the knowledge on another type without puting many lines of code here – yonutix Nov 04 '14 at 15:25