Haskell, class 中的函数声明
Haskell, a function declaration in a class
我正在尝试为多态 class 树创建一些实例,但我不明白,
看,我的代码是:
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
):
class Tree t where
getName :: t a -> a
instance Tree BTree where
getName (BLeaf name) = name
getName (BBranch name lhs rhs) = name
如果您需要根据元素类型改变实例 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
可能不需要写得那么笼统。
我正在尝试为多态 class 树创建一些实例,但我不明白,
看,我的代码是:
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
):
class Tree t where
getName :: t a -> a
instance Tree BTree where
getName (BLeaf name) = name
getName (BBranch name lhs rhs) = name
如果您需要根据元素类型改变实例 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
可能不需要写得那么笼统。