在阅读 QuickCheck Manual 时,我遇到了以下示例:
prop_RevRev xs = reverse (reverse xs) == xs
where types = xs::[Int]
手册接着说:
Properties must have monomorphic types. `Polymorphic' properties, such as the one above, must be restricted to a particular type to be used for testing. It is convenient to do so by stating the types of one or more arguments in a
where types = (x1 :: t1, x2 :: t2, ...)
clause. Note that types is not a keyword; this is just a local declaration which provides a convenient place to restrict the types of x1, x2 etc.
我以前从未在 Haskell 中看到过这样的技巧。这是我真正遇到的问题:
prop_RevRev :: [Int] -> Bool
prop_RevRev xs = reverse (reverse xs) == xs
where
构成类型声明的“特殊”语法?或者它是一致的和合乎逻辑的(如果是这样,如何?)? 最佳答案
where
不是类型声明的特殊语法。例如,这有效:
prop_RevRev :: [Int] -> Bool
prop_RevRev xs = ys == xs
where ys = reverse (reverse xs)
这也是:
prop_RevRev xs = ys == xs
where ys = reverse (reverse xs)
ys :: [Int]
where type = (xs :: [Int])
的优势|超过 prop_RevRev :: [Int] -> Bool
是在后一种情况下您必须指定返回类型,而在前一种情况下编译器可以为您推断它。如果您有一个非 Boolean
,这将很重要。属性,例如:prop_positiveSum xs = 0 < length xs && all (0 <) xs ==> 0 < sum xs
where types = (xs :: [Int])
关于haskell - 'where' 中的类型声明——这是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7635720/