【问题标题】:Function definition problems (No instance for … arising from)函数定义问题(没有实例...产生于)
【发布时间】:2014-02-11 21:40:50
【问题描述】:

我已经定义了以下函数来查找列表的倒数第二个元素(Int、string...)

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

我收到以下错误

(Num (IO a0)) 没有实例 源自文字42' Possible fix: add an instance declaration for (Num (IO a0)) In the expression: 42 In the first argument ofmyButLast',即[42]' In the first argument ofshouldThrow',即`myButLast [42]'

这是什么意思以及如何解决?可能是需要类的约束吗?

我想处理字符串和 myButLast 中的任何内容。我所有其他包含多个元素的测试都有效。

【问题讨论】:

  • myButLast [x, _] = x 匹配恰好包含两个元素的列表。如果你想用一个元素匹配一个列表:myButLast [x] = xmyButLast (x:[]) = x

标签: haskell


【解决方案1】:

shouldThrow 的类型为 Exception e => IO a -> Selector e -> Expectation。这意味着第一个参数应该在 IO monad 中。为了使用纯函数,可以使用evaluate函数:

evaluate (myButLast [42]) `shouldThrow` anyException

顺便说一句,您可能需要测试特定错误以确保它不会在某些时候被错误地更改:

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

【讨论】:

  • 评估的导入是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2020-10-02
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多