Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this Haskell ADT derive Show?

The ADT is the free monad:

data Free f r = Free (f (Free f r)) | Pure r

I'd like for it to derive Show so that I can print it out when working with it. For example, if I have the following:

data T next = A next | B next deriving (Show)
aa = Free $ A $ Free $ B $ Pure ()

As it is right now, I get the following error if I add deriving (Show) to the Free ADT:

No instance for (Show (f (Free f r)))
      arising from the first field of ‘Free’ (type ‘f (Free f r)’)
    Possible fix:
      use a standalone 'deriving instance' declaration,
        so you can specify the instance context yourself
    When deriving the instance for (Show (Free f r))

I'd like for show aa to result in a printable string. Is this possible?

like image 797
Ana Avatar asked Jan 08 '23 19:01

Ana


1 Answers

As the error message hinted, you need to use an extension called StandaloneDeriving, which lets you specify the constraints on the derived instance explicitly. You also need to enable UndecidableInstances to support the constraint you actually need.

{-# LANGUAGE StandaloneDeriving, UndecidableInstances #-}

deriving instance (Show r, Show (f (Free f r))) => Show (Free f r)
like image 82
Tikhon Jelvis Avatar answered Jan 18 '23 08:01

Tikhon Jelvis