开发者

How to define that a generic type is "printable"

开发者 https://www.devze.com 2023-04-06 05:01 出处:网络
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 t

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号