函数定义问题(无实例……产生) [英] Function definition problems (No instance for … arising from)
问题描述
我已经定义了以下函数来查找某物(整数,字符串...)列表的倒数第二个元素
I have defined the following function to find the penultimate element of a list of something (Int, string...)
myButLast :: [a] -> a
myButLast [] = error "myButLast: empty list"
myButLast [x, _] = x
myButLast (_:xs) = myButLast xs
当我用hspec对其进行测试
When I test it with hspec
it "returns an error for list of one element" $ do
myButLast [42] `shouldThrow` anyException
我收到以下错误
没有实例用于(Num(IO a0)) 由文字
42' Possible fix: add an instance declaration for (Num (IO a0)) In the expression: 42 In the first argument of
myButLast'产生,即[42]' In the first argument of
shouldThrow',即'myButLast [42]'
No instance for (Num (IO a0)) arising from the literal
42' Possible fix: add an instance declaration for (Num (IO a0)) In the expression: 42 In the first argument of
myButLast', namely[42]' In the first argument of
shouldThrow', namely `myButLast [42]'
这是什么意思,以及如何解决?可能是需要上课的限制吗?
What does it mean and how to fix it ? May be a constraint of class needed?
我想处理String和myButLast中任何内容的列表.我所有其他带有倍数元素的测试都可以正常工作.
I want to handle String and list of anything in myButLast. All my other tests with multiples elements works.
推荐答案
shouldThrow
具有类型Exception e => IO a -> Selector e -> Expectation
.这意味着第一个参数应该在IO monad中.为了使用纯函数,可以使用evaluate
函数:
shouldThrow
has the type Exception e => IO a -> Selector e -> Expectation
. This means that the first argument should be in the IO monad. In order to use pure functions, you can use the evaluate
function:
evaluate (myButLast [42]) `shouldThrow` anyException
顺便说一句,您可能要测试特定的错误,以确保在某个时候不会被错误地更改:
Incidentally, you might want to test for the specific error to make sure it doesn't get mistakenly changed at some point:
evaluate (myButLast [42]) `shouldThrow` errorCall "myButLast: empty list"
这篇关于函数定义问题(无实例……产生)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!