ghc 源文件中 ghci 中最接近 :type 的等价物是什么?

What is the nearest equivalent of :type in ghci in a ghc source file?

如果我想比较类型或只是在 Haskell 源文件中打印类型信息,我有哪些选择?

Typed holes!

foo x =  length [x] + _

使用 GHC 编译或加载到 GHCi 将得到:

Found hole ‘_’ with type: Int
Relevant bindings include
  x :: a
  foo :: a -> Int

我最近发现的一个方便的技巧是将类型化的孔与 asTypeOf1.

结合使用

如果您有 可以 编译的代码,并且您想知道其中表达式的类型,用空洞替换该表达式有时会把事情搞砸,因为在:

           -- what is the type of this part, I wonder?
f xs = 3 * length xs

length xs 替换为 _ 报告:

foo.hs:1:12: Warning:
    Found hole ‘_’ with type: a
    Where: ‘a’ is a rigid type variable bound by
               the inferred type of f :: t -> a at foo.hs:1:1

length xs 肯定不是 a!

类型

但是如果你使用 asTypeOf,你可以将 length xs 留在那里 并且 插入一个必须与它具有相同类型的孔:

f xs = 3 * (length xs `asTypeOf` _)

现在我们得到:

foo.hs:1:34: Warning:
    Found hole ‘_’ with type: Int

好多了。


1 asTypeOfconst 完全相同,因为它 returns 它的第一个参数而完全忽略它的第二个。但是它的类型强制第二个参数与第一个参数相同;它被设计成带有反引号的中缀。

它是为当你有一个过于多态的子表达式而 GHC 抱怨不明确的类型变量时设计的;您可以使用内联类型声明,但有时没有 ScopedTypeVariables 扩展名是不可能的。如果您有另一个正确类型的值,则可以使用 asTypeOf 到 "select" 来自多态表达式的适当大小写,而无需更改表达式返回的值。

我在这里使用的是 "backwards" 来自预期的案例;我想让左边的东西限制右边(忽略的)孔的类型,而不是相反。