【发布时间】:2018-10-14 13:26:44
【问题描述】:
我在 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未在let ...部分的let-in语句中定义。
标签: haskell quickcheck hspec