1
votes

I'm having some trouble creating a function to print the contents of a Tree. My definition for the data type Tree is as follows:

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)

The code for printing the tree is:

printTree :: Tree a -> String
printTree (Node a left right) = printTreeAux (Node a left right) 0

printTreeAux :: Tree a -> Int -> String
printTreeAux EmptyTree _ = ""
printTreeAux (Node a left right) depth = (replicate (6 * depth) ' ') ++ show a ++ "\n" ++ (printTreeAux left (depth + 1)) ++ "\n" ++ (printTreeAux right (depth + 1))

And I'm getting the following error when loading the file to Hugs:

ERROR file:.\Tree.hs:30 - Cannot justify constraints in explicitly typed binding
*** Expression    : printTreeAux
*** Type          : Tree a -> Int -> String
*** Given context : ()
*** Constraints   : Show a

I already searched for some clarification but found nothing that could really help... Thanks in advance.

1

1 Answers

3
votes

Change:

printTree :: Tree a -> String
printTree (Node a left right) = printTreeAux (Node a left right) 0

to:

printTree :: Tree a -> String
printTree x = printTreeAux x 0

or even better:

printTree :: Tree a -> String
printTree = (flip printTreeAux) 0

There's no need to pattern match on printTree as you are forwarding the argument to printTreeAux. In fact with your pattern matching, EmptyTree will never be matched in printTree and therefore generate an error.

You should also add a constraint on a to request that it's Showable, otherwise show a is not going to compile:

printTree :: (Show a) => Tree a -> String

and:

printTreeAux :: (Show a) => Tree a -> Int -> String

As you can see, with those fixes, the program will compile, and run, just fine.