繁体   English   中英

Haskell,类中的函数声明

[英]Haskell, a function declaration in a 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-function?

对类型构造函数使用类型参数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

可能你不需要这么普遍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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