You need to enable JavaScript to run this app. Haskell quickBatch测试Ap ZipList Monoid时EqProp实现编译报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Haskell quickBatch测试Ap ZipList Monoid时EqProp实现编译报错如何解决

编译错误根因

你当前实现的instance Eq a => EqProp (Ap f a)是面向所有容器f的全局泛型实例,实例内解构Ap l得到的l类型为抽象的f a,但你直接将l传入take函数——take仅接受普通列表[a]作为输入,编译器无法将任意抽象类型f a匹配到列表结构,因此抛出刚性类型变量不匹配的报错。
本质上是你想做的“截断列表避免无限循环”的逻辑仅适配ZipList场景,但却把这套逻辑写成了所有Applicative容器通用的规则,类型边界完全错位。

调整方案

完全不需要推翻你原本的EqProp截断对比的核心思路,只要收窄实例的适用范围即可,没必要为了泛型写额外的抽象层:

  • 删除当前无边界的泛型EqProp实例,这类通用实例中硬编码列表操作必然触发类型不匹配
  • 单独为Ap ZipList a实现对应EqProp逻辑,解构时直接取出ZipList包裹的原始列表类型,此时再执行take截断操作类型完全匹配
  • 截断长度保留3000的取值即可,既可以应对quickcheck生成的无限ZipList场景,也不会因为截断过短丢失测试有效性
可直接运行的完整测试代码

首先确认需要导入的依赖模块(transformers 提供ZipList,quickcheck-classes 提供quickBatch与monoid属性测试):

import Data.Functor.ZipList (ZipList(..))
import Data.Monoid (Sum(..))
import Test.QuickCheck (Arbitrary(..))
import Test.QuickCheck.Property (eq, EqProp(..))
import Test.QuickCheck.Classes (monoid)
import Test.QuickCheck (quickBatch)

newtype Ap f a = Ap { getAp :: f a }
  deriving (Eq, Show)

instance (Applicative f, Semigroup a) => Semigroup (Ap f a) where
  Ap xs <> Ap ys = Ap $ liftA2 (<>) xs ys

instance (Applicative f, Monoid a) => Monoid (Ap f a) where
  mempty = Ap $ pure mempty
  mappend (Ap xs) (Ap ys) = Ap $ liftA2 mappend xs ys

app :: Ap ZipList (Sum Int)
app = Ap (ZipList [1,2 :: Sum Int])

-- 这个泛型Arbitrary实例无硬编码类型操作,可以保留
instance Arbitrary (f a) => Arbitrary (Ap f a) where
  arbitrary = Ap <$> arbitrary

-- 收窄到ZipList场景的EqProp实现,类型完全匹配
instance Eq a => EqProp (Ap ZipList a) where
  xs =-= ys = truncatedXs `eq` truncatedYs
    where
      -- 逐层解构出ZipList内部的原始列表
      Ap (ZipList l1) = xs
      Ap (ZipList l2) = ys
      -- 截断到3000长度,避免无限列表导致测试卡死
      truncatedXs = take 3000 l1
      truncatedYs = take 3000 l2

main :: IO ()
main = quickBatch $ monoid app
运行效果说明

修正后的代码会正常编译执行,quickBatch monoid 会自动校验Monoid类型类要求的左单位元、右单位元、结合律三类属性,因为EqProp实现了截断对比逻辑,哪怕测试用例生成了超长/无限长度的ZipList也不会触发死循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 01:45:04