Class Haskell,类中的函数声明

Class Haskell,类中的函数声明,class,haskell,polymorphism,instance,Class,Haskell,Polymorphism,Instance,我正在尝试为一个变形类树创建一些实例,但我不明白 看,我的代码是: data BTree a = BLeaf a | BBranch a (BTree a) (BTree a) deriving(Show) data TTree a = TLeaf a | TBranch a (TTree a) (TTree a) (TTree a) deriving(Show) class Tree a where getName :: a -> a -- How should i decl

我正在尝试为一个变形类树创建一些实例,但我不明白

看,我的代码是:

data BTree a = BLeaf a | BBranch a (BTree a) (BTree a) deriving(Show)
data TTree a = TLeaf a | TBranch a (TTree a) (TTree a) (TTree a) deriving(Show)

class Tree a where

    getName :: a -> a -- How should i declare this function?

instance Tree (BTree a) where

    getName (BLeaf name) = name
    getName (BBranch name lhs rhs) = name

instance Tree (TTree a) where

    getName (TLeaf name) = name
    getName (TBranch name lhs mhs rhs) = name

test1 = getName (BLeaf 1)
test2 = getName (TLeaf 1)
GHCI说:

Couldn't match expected type `a' with actual type `BTree a'

那么,我应该如何声明getName函数呢?

对类型构造函数使用类型类参数
t
(比如
BTree
TTree
,与
BTree a
TTree a
不同):

如果需要根据元素类型
a
改变实例,则需要多参数类:

{-# LANGUAGE MultiParamTypeClasses #-}

class Tree t a where
    getName :: t a -> a

instance Tree BTree Int where
    getName (BLeaf name) = name+1
    getName (BBranch name lhs rhs) = name*2

instance Tree BTree Char where
    getName (BLeaf name) = name
    getName (BBranch name lhs rhs) = name
也许你不需要把它说得这么笼统

{-# LANGUAGE MultiParamTypeClasses #-}

class Tree t a where
    getName :: t a -> a

instance Tree BTree Int where
    getName (BLeaf name) = name+1
    getName (BBranch name lhs rhs) = name*2

instance Tree BTree Char where
    getName (BLeaf name) = name
    getName (BBranch name lhs rhs) = name