避免出现警告,默认将以下约束键入"Integer" [英] Avoid warning Defaulting the following constraint(s) to type `Integer'
问题描述
我定义了以下函数来反转Int或字符串列表:
I have defined the following function to reverse a list of Int or string:
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x:xs) = (myReverse xs) ++ [x]
我对hspec的测试:
My test with hspec:
describe "myReverse" $ do
it "returns the inversed list of the given list" $ do
myReverse [1,2,3,4] `shouldBe` [4,3,2,1]
it "returns the inversed string of the given string" $ do
myReverse "A man, a plan, a canal, panama!" `shouldBe` "!amanap ,lanac a ,nalp a ,nam A"
像这样我得到警告
tests/OneToTenSpec.hs:69:24:
Warning: Defaulting the following constraint(s) to type `Integer'
(Eq a0)
arising from a use of `shouldBe' at tests/OneToTenSpec.hs:69:24-33
(Num a0)
arising from the literal `1' at tests/OneToTenSpec.hs:69:15
(Show a0)
arising from a use of `shouldBe' at tests/OneToTenSpec.hs:69:24-33
In a stmt of a 'do' block:
myReverse [1, 2, 3, 4] `shouldBe` [4, 3, 2, 1]
In the second argument of `($)', namely
`do { myReverse [1, 2, ....] `shouldBe` [4, 3, ....] }'
In a stmt of a 'do' block:
it "returns the inversed list of the given list"
$ do { myReverse [1, 2, ....] `shouldBe` [4, 3, ....] }
所以我对测试进行了以下更改
So I made the following change on the test
myReverse [1 :: Int,2,3,4] `shouldBe` [4,3,2,1]
除了定义列表元素的类型之外,还有另一种避免此警告的方法吗?
Is there is another way to avoid this warning than defining the type of an element of the list ?
推荐答案
不适用于数字文字.由于文字的类型为Num a => a
,并且我们将其提供给a
中具有多态性的函数,因此没有提示将a
解析为什么.
Not with numeric literals. Since literals have the type Num a => a
and we're feeding it to a function that's polymorphic in a
, there are no hints as to what to resolve a
to.
好消息是,这正是默认设置的工作方式,您不必担心!该警告虽然很烦人,但我可以想到两种避免该警告的方法
The good news is that this is exactly how defaulting is meant to work and you have nothing to worry about! The warning is annoying though, I can think of two ways to avoid it
- 使用显式类型签名
- 不要使用数字文字
2在您的情况下可能是最好的,从类型上我们知道元素的类型不会影响其功能,因此您可以自由使用Bool
2 will probably be the best in your scenario, we know from the type that the type of element can't impact its function, so you're free to use Bool
myReverse [True, False] `shouldBe` [False, True]
顺便说一句,您当前的实现是O(n^2)
,并且O(n)
是可能的,我留给您了解如何实现:)
As an aside your current implementation is O(n^2)
and O(n)
is possible, I'll leave it to you to figure out how though :)
这篇关于避免出现警告,默认将以下约束键入"Integer"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!