haskell - 'where' 中的类型声明——这是怎么回事?

标签 haskell types where-clause

在阅读 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构成类型声明的“特殊”语法?或者它是一致的和合乎逻辑的(如果是这样,如何?)?
  • 这是使用标准还是传统的 Haskell?
  • 最佳答案

    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/

    相关文章:

    list - 比较haskell中的字符串内容

    haskell - Haskell进入元组

    sql - 货币和整数数据类型之间的区别

    r - 如何在日期不进行类型转换的情况下将列表转换为数据框

    php mysql where 子句使用日期

    haskell - Haskell 中的幻像类型

    haskell - 为什么 Gloss 不能以原始分辨率渲染?

    types - Elixir 是一种将 float 和整数都转换为位串的函数吗?

    java - Hibernate:左连接中的 where 子句无法正常工作

    linq - 动态 Linq 帮助,不同的错误取决于作为参数传递的对象?