You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Haskell中编写面向Finite域函数的相等性判断函数

实现思路

两个函数相等的数学定义为:对定义域内的所有输入值,两个函数的输出都相等。由于Finite类型类同时继承了Bounded和Enum约束,我们可以枚举定义域的所有合法取值,逐一验证两个函数的输出是否一致即可完成相等性判断。

具体实现

首先定义Finite类型类,以及覆盖所有满足约束的类型的通用实例(需要开启对应GHC扩展):

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}

class (Bounded a, Enum a) => Finite a
instance (Bounded a, Enum a) => Finite a

然后实现equals函数:

equals :: (Finite a, Eq b) => (a -> b) -> (a -> b) -> Bool
equals f g = all (\x -> f x == g x) [minBound .. maxBound]
测试验证

以你给出的neg函数为例:

import Data.Int (Int8)

neg :: Int8 -> Int8
neg n = -n

运行测试结果和预期一致:

*Main> equals neg (\x -> x)
False
*Main> equals neg (neg . neg)
True
*Main> equals not not -- Bool域测试
True

内容的提问来源于stack exchange,提问作者user17136256

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:15:04