让我们考虑一个拥有多个构造函数的数据类型:
data T = Alpha Int | Beta Int | Gamma Int Int | Delta Int
我想编写一个函数来检查两个值是否由相同的构造函数产生:
sameK (Alpha _) (Alpha _) = True
sameK (Beta _) (Beta _) = True
sameK (Gamma _ _) (Gamma _ _) = True
sameK _ _ = False
维护sameK
并不是很有趣,因为它很难被轻易地检查其正确性。例如,当向T
添加新构造函数时,很容易忘记更新sameK
。我故意省略了一行代码以作为例子。
-- it’s easy to forget:
-- sameK (Delta _) (Delta _) = True
问题是如何避免在
sameK
中使用样板代码?或者如何确保它检查所有T
构造函数?
我找到的解决方法是为每个构造函数使用单独的数据类型,派生
Data.Typeable
,并声明一个公共类型类。但我不喜欢这个解决方案,因为它可读性较差,否则只需一个简单的代数类型即可适用于我:{-# LANGUAGE DeriveDataTypeable #-}
import Data.Typeable
class Tlike t where
value :: t -> t
value = id
data Alpha = Alpha Int deriving Typeable
data Beta = Beta Int deriving Typeable
data Gamma = Gamma Int Int deriving Typeable
data Delta = Delta Int deriving Typeable
instance Tlike Alpha
instance Tlike Beta
instance Tlike Gamma
instance Tlike Delta
sameK :: (Tlike t, Typeable t, Tlike t', Typeable t') => t -> t' -> Bool
sameK a b = typeOf a == typeOf b