让我们考虑以下代码片段:
blah :: a -> b -> a
blah x y = ble x where
ble :: b -> b
ble x = x
这在 GHC 下编译得很好,这基本上意味着
b
从第 3 行开始,与 b
不同。从第一行开始。我的问题很简单:有没有办法在
ble
的类型声明中以某种方式关联?到外部上下文中使用的类型,即 blah
的类型声明?显然,这只是一个示例,而不是类型声明的真实用例。
最佳答案
ScopedTypeVariables 可以做到这一点扩大。您需要使用显式 forall 将类型变量带入范围。
blah :: forall a b. a -> b -> a
blah x y = ble x where
ble :: b -> b
ble x = x
尝试在启用 ScopedTypeVariables 的情况下加载此定义会给出:
foo.hs:2:16:
Couldn't match type `a' with `b'
`a' is a rigid type variable bound by
the type signature for blah :: a -> b -> a at foo.hs:2:1
`b' is a rigid type variable bound by
the type signature for blah :: a -> b -> a at foo.hs:2:1
In the first argument of `ble', namely `x'
In the expression: ble x
In an equation for `blah':
blah x y
= ble x
where
ble :: b -> b
ble x = x
你可以看出 GHC 解释了这两个
b
s 为同一类型,因为错误表明 a
和 b
绑定(bind)在同一条线上。
关于haskell - 如何与外部上下文中的类型相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8400150/