How to define that a generic type is "printable"
I have to print on pre-order a 开发者_Go百科polymorphic Tree type. I'm having some trouble because my generic type t may not be "printable". Does anyone knows how to sold this? Is there anyway to tell haskell to only accept "printable" types? (print on the console, soo it should be something like "Show")
Here is the code:
import Char
data Tree t =
NilT |
Node t (Tree t) (Tree t)
instance Show (Tree t) where
show = func
func :: (Tree t) -> String
func (NilT) = ""
func (Node t a b) = t ++ (func a) ++ (func b)
Thanks!
Your can demand that t
be an instance of Show
, both in the instance declaration and the following type declaration:
instance Show t => Show (Tree t)
func :: Show t => Tree t -> String
To use this, your pre-order traversal will need to call show
.
func (Node t a b) = show t ++ func a ++ func b
精彩评论