诀窍是创建一个类型类,您将为其定义函数实例和返回类型实例。事实上,它是一个Bool
根本不是问题。
我们正在尝试编写一个函数,它接受一个可变参数并返回一个Bool
,所以我们将使用这样的函数定义一个类型类。
class Stmt a where
tautology :: a -> Bool
接下来,我们为可变参数函数的返回类型定义一个实例。在这种情况下,那就是Bool
.
-- A Bool is a tautology if it's True.
instance Stmt Bool where
tautology = id
关键部分是函数的下一个实例Bool
参数,其返回类型是我们类中的某种类型。这样,如果函数采用多个参数,则该实例将被多次应用。
-- A function is a tautology if it always returns a tautology.
instance Stmt b => Stmt (Bool -> b) where
tautology f = tautology (f True) && tautology (f False)
这样写需要FlexibleInstances
因为Bool
在第二个实例头中。要对纯 Haskell 98 执行相同操作,我们需要使用适当约束的类型变量。我们可以例如使用Bounded
and Enum
(两者都有实例Bool
),或者您可以创建自己的类来构造适当的输入。
instance (Enum a, Bounded a, Stmt b) => Stmt (a -> b) where
tautology f = all (tautology . f) [minBound .. maxBound]
我们就完成了。让我们尝试一下:
> tautology $ \x y -> (not x && not y) == not (x && y)
False
> tautology $ \x y -> (not x && not y) == not (x || y)
True