[英]Hspec & QuickCheck - Ambiguous type variable a0?
我在Haskell中編寫了一個函數,該函數接受任意元素的列表並返回(映射)元組列表。 每個元組都包含原始元素和一個分數,列表中的所有分數都加1(因此,我只需使用1 ``div`` length xs
一次計算分數並將其應用於所有元素)。 這是代碼:
uniform :: [a] -> [(a, Int)]
uniform xs = map (\x -> (x, prob)) xs
where prob = 1 `div` (length xs)
(免責聲明:這實際上是一個稍微簡化的版本,但我產生的行為完全相同,因此希望足夠了。)
我試圖通過使用Hspec和Quickcheck的基於屬性的測試來涵蓋這一點:
spec = do
describe "uniform" $ do
it "produces a uniform distribution summing to 1" $ property $
let totalProbability ((_, p):xs) = p + (totalProbability xs)
in (\xs -> (totalProbability $ uniform xs) `shouldBe` 1)
但是,當我運行此命令時,出現以下錯誤:
• Ambiguous type variable ‘a0’ arising from a use of ‘property’
prevents the constraint ‘(Arbitrary a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance (Arbitrary a, Arbitrary b) => Arbitrary (Either a b)
-- Defined in ‘Test.QuickCheck.Arbitrary’
instance Arbitrary Ordering
-- Defined in ‘Test.QuickCheck.Arbitrary’
instance Arbitrary Integer
-- Defined in ‘Test.QuickCheck.Arbitrary’
...plus 19 others
...plus 62 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the second argument of ‘($)’, namely
‘property
$ let totalProbability ((_, p) : xs) = p + (totalProbability xs)
in (\ xs -> (totalProbability $ uniform xs) `shouldBe` 1)’
In a stmt of a 'do' block:
it "produces a uniform distribution summing to 1"
$ property
$ let totalProbability ((_, p) : xs) = p + (totalProbability xs)
in (\ xs -> (totalProbability $ uniform xs) `shouldBe` 1)
In the second argument of ‘($)’, namely
‘do it "produces a uniform distribution summing to 1"
$ property
$ let totalProbability ((_, p) : xs) = ...
in (\ xs -> (totalProbability $ uniform xs) `shouldBe` 1)’
| 12 | 它“產生一個總和為1的均勻分布”。 ^^^^^^^^^^ ...
我猜想在某個地方我沒有給QuickCheck有關如何生成測試值的足夠信息,但是我不確定從這里去哪里。
任何幫助將不勝感激。
謝謝!
您需要為xs
指定類型:這是字符串列表嗎? 整型? 布爾值? 這樣,QuickCheck可以生成該類型的隨機樣本。
您可以編寫,例如:
...
in (\xs -> (totalProbability $ uniform (xs :: [Int])) `shouldBe` 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.