Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Exception 如何在Haskell中使用testpack中的assertRaises?_Exception_Haskell_Exception Handling - Fatal编程技术网

Exception 如何在Haskell中使用testpack中的assertRaises?

Exception 如何在Haskell中使用testpack中的assertRaises?,exception,haskell,exception-handling,Exception,Haskell,Exception Handling,我正在学习Haskell,我想做TDD。 我试图测试函数是否引发预期的异常。 我正在使用HUnit和 testpack提供了assertRaises函数,但我无法编译代码:( 以下是我的源代码: module Main where import Test.HUnit import Test.HUnit.Tools import Control.Exception foo n | n > 2 = throw ( IndexOutOfBounds ( "Index out of boun

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

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操作


试着用
(evaluate(foo 4))
替换
(foo 4)

由于懒惰,我认为
return
在这里不起作用。
evaluate
应该可以做这项工作。@hammar我太马虎了。谢谢。