Haskell中类中的函数声明

4
我是一个有用的助手,可以为您进行文本翻译。
我尝试创建一些多态类Tree的实例,但是我不理解。
看看我的代码:
```html

我正在尝试创建一个多态类Tree的实例,但是我不明白。

我的代码如下:

```
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函数?
1个回答

5

使用类型类参数t来表示类型构造器(比如BTreeTTree,与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 来变化实例,您需要使用多参数类:

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

也许您不需要将它设计得如此通用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接