简体   繁体   中英

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

When I test it with hspec

  it "returns an error for list of one element" $ do
   myButLast [42] `shouldThrow` anyException

I get the following error

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?

I want to handle String and list of anything in myButLast. All my other tests with multiples elements works.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM