Robert Onslow
Robert Onslow

Reputation: 215

Recursive instance definitions

I have a recursive data definitions:

data Checked a =  forall b. Checked (Either (Warning, Maybe (Checked b), a) a)

I need to define Show recursively:

instance (Show a) => Show (Checked a) where
  show (Right v) = show v
  show (Left (w, Nothing, v) = show w ++ show v
  show (Left (w, Just ch, v) = show w ++ show v ++ "caused by" ++ show ch --recursive here

GHC gives

 Could not deduce (Show b) arising from a use of `show'
  from the context (Show a)
  bound by the instance declaration at Checked.hs:29:10-35
  Possible fix:
   add (Show b) to the context of
    the data constructor `Checked'
    or the instance declaration
  In the second argument of `(++)', namely `show ch'

If I add (Show b) to the constraints on the instance definition, GHC gives:

 Ambiguous constraint `Show b'
  At least one of the forall'd type variables mentioned by the constraint
  must be reachable from the type after the '=>'
In the instance declaration for `Show (Checked a)'

Is there a next step I should take to get this to compile?

Upvotes: 1

Views: 922

Answers (2)

Satvik
Satvik

Reputation: 11218

Add Show constraint to the data type definition.

data Checked a =  forall b. Show b => Checked (Either (Warning, Maybe (Checked b), a) a)

You can also use constraint kinds as

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}

data Checked a c =  forall b. c b =>  Checked (Either (Maybe (Checked b c), a) a)

instance (Show a) => Show (Checked a Show) where
 show (Checked (Right v)) = show v
 show (Checked (Left (Nothing, v))) = show v
 show (Checked (Left (Just ch, v))) = show v ++ "caused by" ++ show ch

Upvotes: 3

Sjoerd Visscher
Sjoerd Visscher

Reputation: 12010

You need to add the Show b restriction to the data type:

data Checked a = forall b. Show b => Checked (Either (Warning, Maybe (Checked b), a) a)

instance Show a => Show (Checked a) where
  show (Checked (Right v)) = show v
  show (Checked (Left (w, Nothing, v))) = show w ++ show v
  show (Checked (Left (w, Just ch, v))) = show w ++ show v ++ "caused by" ++ show ch

Upvotes: 5

Related Questions