您的位置:首页 > 其它

定义类型类

2015-07-07 10:17 274 查看
data Color = Red|Blue|Green

class BasicEq a where
isEqual :: a->a->Bool
isEqual x y = not (isNotEqual x y)

isNotEqual :: a->a->Bool
isNotEqual x y = not (isEqual x y)

instance  BasicEq Bool where
isEqual False False = True
isEqual True True = True
isEqual _ _ = False

instance BasicEq Color where
isEqual Red Red = True
isEqual Blue Blue = True
isEqual Green Green = True
isEqual _ _ = True

定义类型类使用

class className xxx where

常用的函数show

其函数签名

*Main> :type show
show :: Show a => a -> String

可知它是类型类Show里的一个方法,方法签名如上

同理看看我们的自定义

*Main> :type isEqual
isEqual :: BasicEq a => a -> a -> Bool
*Main>


使用时可以指定返回类型

*Main> (isEqual True False ):: Bool
False

指定输入类型

*Main> isEqual Blue (Blue::Color)
True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: