gpt4 book ai didi

exception - 如何在 Haskell 中使用 testpack 中的 assertRaises?

转载 作者:行者123 更新时间:2023-12-04 05:55:03 25 4
gpt4 key购买 nike

我正在学习 Haskell,我想做 TDD。
我正在尝试测试函数是否引发预期异常。
我正在使用 HUnit 和 testpack .

testpack 提供了一个 assertRaises 函数,但我无法编译我的代码 :(

这是我的源代码:

module Main where
import Test.HUnit
import Test.HUnit.Tools
import Control.Exception

foo n | n > 2 = throw ( IndexOutOfBounds ( "Index out of bounds : " ++ ( show n ) ) )
foo n | otherwise = n

testException = TestCase( assertRaises "throw exception" ( IndexOutOfBounds "Index out of bounds : 4" ) ( foo 4 ) )

main = runTestTT ( TestList [ testException ] )

当我用 ghc 编译它时,我收到以下错误消息:
test_exceptions.hs:10:107:
No instance for (Ord (IO a0))
arising from a use of `foo'
Possible fix: add an instance declaration for (Ord (IO a0))
In the third argument of `assertRaises', namely `(foo 4)'
In the first argument of `TestCase', namely
`(assertRaises
"throw exception"
(IndexOutOfBounds "Index out of bounds : 4")
(foo 4))'
In the expression:
TestCase
(assertRaises
"throw exception"
(IndexOutOfBounds "Index out of bounds : 4")
(foo 4))

test_exceptions.hs:10:111:
No instance for (Num (IO a0))
arising from the literal `4'
Possible fix: add an instance declaration for (Num (IO a0))
In the first argument of `foo', namely `4'
In the third argument of `assertRaises', namely `(foo 4)'
In the first argument of `TestCase', namely
`(assertRaises
"throw exception"
(IndexOutOfBounds "Index out of bounds : 4")
(foo 4))'

怎么了 ?

最佳答案

assertRaises期望它的第三个参数是 IO 操作(类型为 IO a),但返回类型来自 foo是一个数字(类型为 (Num a, Ord a) => a ),而不是 IO 操作。

尝试更换 (foo 4)(evaluate (foo 4)) .

关于exception - 如何在 Haskell 中使用 testpack 中的 assertRaises?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9597700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com