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

Time:11-06

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

CodePudding user response:

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)
  • Related