让我们考虑一个具有许多构造函数的数据类型:
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