2016-11-18 15 views
4

iが多クラスツリーのためのいくつかのインスタンスを作成しようとしていますが、私はそれを得るいけない、ハスケル、クラス内の関数宣言

見て、私のコードは次のとおりです。

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-functionをどのように宣言する必要がありますか?

答えて

5

型コンストラクタのための型クラスのパラメータtを使用します(のようなBTreeまたはTTree、およびBTree aTTree aとは違って):

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

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

あなたは要素の型aに応じて変化するようにインスタンスが必要な場合は、複数の必要-parameterクラス:

{-# 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 

多分それほど一般的にする必要はありません。

関連する問題