Show function for polymorphic type

自闭症网瘾萝莉.ら 提交于 2019-12-25 03:58:12

问题


I'm trying to define the Show function for the polymorphic Tree type. Could anyone help me?

import Char

data Tree t =
    NilT |
    Node t (Tree t) (Tree t)

class Mar t where
    maior :: t -> String

instance Mar Tree where
    maior (NilT) = "a" 
    maior (Node t a b) = "b"

instance Show Tree where
    show = maior

Thanks a Lot!


Solution (given by ivanm):

import Char

data Tree t =
    NilT |
    Node t (Tree t) (Tree t)

class Mar t where
    maior :: t -> String

instance Mar (Tree t) where
    maior (NilT) = "a" 
    maior (Node t a b) = "b"

instance Show (Tree t) where
    show = maior

回答1:


Is there any particular reason that you aren't using deriving Show? The Show and Read classes are meant to provide really basic serialisation/deserialisation which (usually) produce valid Haskell code.

But for what you want, I think the error is going back to your Mar class. As defined, the instance is for kind * -> * (e.g. Maybe as opposed to Maybe Int). What you probably meant is to have instance Mar (Tree t) where ....




回答2:


data Tree t =
    NilT |
    Node t (Tree t) (Tree t)
    deriving Show


来源:https://stackoverflow.com/questions/7478878/show-function-for-polymorphic-type

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