Skip to content
Discussions/App Development/Deriving Eq and Show for tuples having more than 5 elementsForum ↗

Deriving Eq and Show for tuples having more than 5 elements

App Development6 posts369 views7 likesLast activity Apr 2022
GY
gyorgybalazsiOP
Apr 2022

Tuples bigger than 5 elements are not instances of the Show typeclass:

instance Show ()

instance (Show a, Show b) => Show (a, b)

instance (Show a, Show b, Show c) => Show (a, b, c)

instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d)

instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e)

Can I somehow circumvent this limitation?

ST
stefanobaghino-da
Apr 2022

If you have such a big tuple, in terms of readability you may probably want to think about turning your tuple in a record with explicit names, which are likely to make your code more readable.

In terms of circumventing the limitation, can you write your own instance where you need it, like so?

instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a, b, c, d, e, f)
GY
gyorgybalazsi
Apr 2022
stefanobaghino-da:

instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a, b, c, d, e, f)

Yeah, thank you, actually it’s easy;

instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a, b, c, d, e, f) where 
  show (a,b,c,d,e,f) = "("<> show a <> "," <> show b <> "," <> show c <> "," <> show d <> "," <> show e <> "," <> show f <> ")"
GA
Gary_Verhaegen
Apr 2022
gyorgybalazsi:

Yeah, thank you, actually it’s easy;

I’d still encourage you to consider the record-with-named-fields approach. There’s a reason we chose not to include Show instances for larger tuples despite it being very easy to do.

GY
gyorgybalazsi
Apr 2022

Yes, generally I don’t use large tuples, this is a special situation where I use a library which uses them and 5 elements are not enough.

ST
stefanobaghino-da
Apr 2022

Is there something in particular that’s preventing you from turning the tuple into a record with explicit names? I don’t want to judge, I’m mostly curious if there’s something we can do to promote what we perceive as good practices. If you have some code to share we’re very happy to have a look. :smiley:

← Back to Discussions