Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

No instance for (Show a) arising from a use of ‘show’. Debug.trace() error

import Debug.Trace
data Tree a = Nil | Branch (Tree a) a (Tree a)   deriving (Eq, Show)

instance Foldable Tree where
    foldr _ ini Nil = ini
    foldr f ini (Branch l x r) = trace (show x) (foldr f (f x (foldr f ini r)) l)
• No instance for (Show a) arising from a use of ‘show’
  Possible fix:
    add (Show a) to the context of
      the type signature for:
        foldr :: forall a b. (a -> b -> b) -> b -> Tree a -> b
• In the first argument of ‘trace’, namely ‘(show x)’
  In the expression: trace (show x) (foldr f (f x (foldr f ini r)) l)
  In an equation for ‘foldr’:
      foldr f ini (Branch l x r)
        = trace (show x) (foldr f (f x (foldr f ini r)) l) 

I don’t understand what’s the problem is. I will be very grateful for your help

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem is that foldr must work for Tree a with any element-type a, including types such as [Integer] -> Double which you can’t possibly show. Thus it is not possible to use show x within the definition. It doesn’t matter that this is just for debugging purposes and you want to debug only, say, the Tree Int case – the compiler needs to have the instance available for all types it could possibly be used with.

As a workaround, you can implement the function first as a Show-restricted version, and only after debugging change it into a Foldable method without the trace parts.

foldrTree :: Show a => (a -> b -> b) -> b -> Tree a -> b
foldrTree _ ini Nil = ini
foldrTree f ini (Branch l x r) = trace (show x) (foldrTree f (f x (foldr f ini r)) l)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading