如何从外部上下文中关联类型

问题描述 投票:0回答:2

让我们考虑以下代码片段:

blah :: a -> b -> a
blah x y = ble x where
    ble :: b -> b
    ble x = x

这在 GHC 下编译得很好,这本质上意味着第三行中的

b
与第一行中的
b
不同。

我的问题很简单:有没有办法以某种方式将

ble
的类型声明与外部上下文中使用的类型(即
blah
的类型声明)相关联?

显然,这只是一个示例,而不是类型声明的实际用例。

haskell types functional-programming ghc type-declaration
2个回答
45
投票

这可以通过 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
解释为同一类型,因为错误表明
a
b
绑定在同一行上。


16
投票

SO是一场狗屎秀。感谢您的搭车。

© www.soinside.com 2019 - 2024. All rights reserved.