简体   繁体   中英

Haskell, a function declaration in a class

i am trying to create some instances for a polymorph class Tree, but i dont get it,

look, my code is:

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 says:

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

So, How should i declare the getName-function?

Use a typeclass parameter t for the type constructor (like BTree or TTree , and unlike BTree a and TTree a ):

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

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

If you need the instances to vary depending on the element type a , you need multi-parameter classes:

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

Probably you don't need to make it so general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM