如何为Haskell中的Bool类型实现Describable类型类?
自定义Describable类型类的Bool实例实现
首先纠正一个误区:你没法直接用deriving (Describable),Haskell默认只支持为少数内置类型类(比如Eq、Show)自动派生实例,自定义类型类除非启用DeriveAnyClass扩展,但这个练习的核心是手动实现类型类实例,所以直接写实例更合适。
完整代码实现
先定义类型类(和书中给出的一致):
class Describable a where describe :: a -> String
然后为Bool手动实现Describable实例:
instance Describable Bool where describe True = "This is the boolean value representing truth" describe False = "This is the boolean value representing falsity"
测试示例
在GHCi里调用的效果:
*Main> describe True "This is the boolean value representing truth" *Main> describe False "This is the boolean value representing falsity"
关于DeriveAnyClass的补充(非练习推荐方式)
如果一定要用deriving语法,需要先开启扩展,但本质还是要手动补全方法(因为DeriveAnyClass只会生成空实例框架):
{-# LANGUAGE DeriveAnyClass #-} class Describable a where describe :: a -> String -- 包装Bool类型来派生 data WrappedBool = WrappedBool Bool deriving (Describable) -- 必须手动实现describe方法,否则会报错 instance Describable WrappedBool where describe (WrappedBool True) = "True: the truthy boolean" describe (WrappedBool False) = "False: the falsy boolean"
显然,直接为Bool手动写实例才是书中练习的本意,能更好地理解类型类的工作机制。
内容的提问来源于stack exchange,提问作者Ahmad Ismail
相关产品推荐
相关产品推荐

