How to define that a generic type is “printable”

泄露秘密 提交于 2019-12-11 11:22:32

问题


I have to print on pre-order a 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!


回答1:


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


来源:https://stackoverflow.com/questions/7479252/how-to-define-that-a-generic-type-is-printable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!