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

使用Dump库打印表达式失败的问题及解决方案咨询

问题解答

1. 解决错误并打印失败参数

你的错误源于[d|xs|]是声明引号(TemplateHaskell语法),它返回[Dec]类型,而counterexample需要的是String类型。要同时打印参数的表达式和对应值,可结合TemplateHaskell的表达式引号[e|...]与showCode函数获取表达式字符串,再拼接参数实际值:

首先添加必要导入:

{-# LANGUAGE TemplateHaskell #-}

module Main where

import Debug.Dump
import Language.Haskell.TH.Syntax (showCode) -- 新增导入
import Test.QuickCheck
import System.Exit

修改属性定义:

prop_ReverseLengthFail :: [Int] -> Property
prop_ReverseLengthFail xs = 
  counterexample 
    (unlines [
        "失败参数:",
        "表达式: " ++ showCode [e|xs|],
        "值: " ++ show xs
      ])
    (length (reverse xs) === length xs + 1)

运行测试失败时,会同时输出参数的表达式和实际取值。

2. 打印被测试的属性表达式

要打印属性本身的表达式(即length (reverse xs) === length xs + 1),同样用表达式引号和showCode,将其加入counterexample的输出内容中:

修改后的属性定义:

prop_ReverseLengthFail :: [Int] -> Property
prop_ReverseLengthFail xs = 
  let propExpr = showCode [e|length (reverse xs) === length xs + 1|]
      paramInfo = unlines [
          "失败参数:",
          "表达式: " ++ showCode [e|xs|],
          "值: " ++ show xs
        ]
  in counterexample 
       (unlines [
           "被测试属性:" ++ propExpr,
           paramInfo
         ])
       (length (reverse xs) === length xs + 1)

测试失败时的输出示例:

*** Failed! Falsifiable (after 1 test):  
被测试属性:length (reverse xs) === length xs + 1
失败参数:
表达式: xs
值: []

内容的提问来源于stack exchange,提问作者F. Zer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:42:39