簡體   English   中英

函數定義問題(無實例……產生)

[英]Function definition problems (No instance for … arising from)

我定義了以下函數來查找某物(整數,字符串...)列表的倒數第二個元素

myButLast :: [a] -> a
myButLast [] = error "myButLast: empty list"
myButLast [x, _] = x
myButLast (_:xs) = myButLast xs

當我用hspec測試時

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

我收到以下錯誤

常量42' Possible fix: add an instance declaration for (Num (IO a0)) In the expression: 42 In the first argument of引起(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' Possible fix: add an instance declaration for (Num (IO a0)) In the expression: 42 In the first argument of ,即[42]' In the first argument of ShouldThrow [42]' In the first argument of ,即“ myButLast [42]”

這是什么意思,以及如何解決? 可能是需要上課的限制嗎?

我想處理字符串和myButLast中任何內容的列表。 我所有其他使用倍數元素的測試均有效。

shouldThrow的類型為Exception e => IO a -> Selector e -> Expectation shouldThrow Exception e => IO a -> Selector e -> Expectation 這意味着第一個參數應該在IO monad中。 為了使用純函數,可以使用evaluate函數:

evaluate (myButLast [42]) `shouldThrow` anyException

順便說一句,您可能想測試特定的錯誤,以確保在某個時候不會被錯誤地更改:

evaluate (myButLast [42]) `shouldThrow` errorCall "myButLast: empty list"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM