【发布时间】: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] = x或myButLast (x:[]) = x
标签: haskell