2
votes

I am trying to implement the Show typeclass for my datatype

data Heap a = Heap {invariant :: a -> a -> Ordering
                   ,arr :: UArray Int a}

When using show on this data I just want it to display the underlying array. I have tried to implement the Show like this:

instance Show a => Show (Heap a) where
  show (Heap i a) = show a

But that gives me the following error:

Heap.hs:12:21: error:
    • Could not deduce (IArray UArray a) arising from a use of ‘show’
      from the context: Show a
        bound by the instance declaration at Heap.hs:11:10-32
    • In the expression: show a
      In an equation for ‘show’: show (Heap i a) = show a
      In the instance declaration for ‘Show (Heap a)’
   |
12 |   show (Heap i a) = show a
   |                     ^^^^^^

I think the problem is something to do with the parameterized types, as if I use Int instead of a like the following code it works fine:

data Heap = Heap {invariant :: Int -> Int -> Bool
                 ,arr :: UArray Int Int}
 
instance Show Heap where
  show (Heap i a) = show a

In GHCI

λ > Heap (>) (array (1,10) [])
array (1,10) [(1,0),(2,0),(3,0),(4,0),(5,0),(6,0),(7,0),(8,0),(9,0),(10,0)]

What exactly am I doing wrong when using the parameterized type?

1

1 Answers

2
votes

Just add the given constraint to your instance context. Like this:

instance (IArray UArray a, Show a) => Show (Heap a) where
  show (Heap i a) = show a

You may need some language extensions; the compiler will tell you which ones.