2014-02-19 60 views
13

我已经定义了下面的函数来扭转Int的列表或字符串:避免警告违约以下约束(S)输入'整数”

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" 

myReverse :: [a] -> [a] 
myReverse [] = [] 
myReverse (x:xs) = (myReverse xs) ++ [x] 

我与hspec测试

喜欢我得到

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, ....] } 

所以我做了测试下列变化警告

myReverse [1 :: Int,2,3,4] `shouldBe` [4,3,2,1] 

是否有另一种方法可以避免此警告,而不是定义列表元素的类型?

回答

19

不适用于数字文字。由于文字的类型为Num a => a,我们将它提供给a中的多态函数,因此没有提示要将a解析为什么。

好消息是,这正是默认的工作方式,您无需担心!该警告是烦人不过,我能想到的两种方式,以避免它

  1. 使用显式类型签名
  2. ,不要使用数字文字

2将可能是在您的情况最好,我们知道,从该元素的类型不能影响其功能的类型,所以你可以自由地使用Bool

myReverse [True, False] `shouldBe` [False, True] 

顺便说一句你当前的实现是O(n^2)O(n)是可能的,我会留给你来弄清楚如何:)

+1

它是'myReverse(x:xs)=最后xs:myReverse(tail(x:xs))'? – Idefixx