显示多态类型的函数

时间:2011-09-20 00:34:19

标签: haskell types tree polymorphism

我正在尝试为多态树类型定义Show函数。有谁可以帮助我?

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

非常感谢!


解决方案(由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

2 个答案:

答案 0 :(得分:4)

您是否有任何特殊原因未使用deriving ShowShowRead类旨在提供真正基本的序列化/反序列化(通常)生成有效的Haskell代码。

但是对于你想要的,我认为错误会回到你的Mar课程。根据定义,该实例适用于* -> *种类(例如Maybe而不是Maybe Int)。您可能想要的是拥有instance Mar (Tree t) where ...

答案 1 :(得分:1)

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