如果我想在Haskell源文件中比较类型或仅打印类型信息,我有哪些选项?
foo x = length [x] + _
Found hole ‘_’ with type: Int
Relevant bindings include
x :: a
foo :: a -> Int
最近我发现的一个有用技巧是将类型洞与asTypeOf
1结合使用。
如果您有编译成功的代码,并且想知道其中某个表达式的类型,有时用类型洞替换该表达式会使事情变得混乱,例如:
-- 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
asTypeOf
与const
完全相同,因为它返回其第一个参数并完全忽略其第二个参数。但是,它的类型强制第二个参数与第一个参数相同;它被设计为在反引号中写入。ScopedTypeVariables
扩展。如果您有另一个正确类型的值,则可以使用asTypeOf
从多态表达式中“选择”适当的情况,而不更改表达式返回的值。