如何与来自外部环境的类型相关联 [英] How to relate to type from outer context

查看:149
本文介绍了如何与来自外部环境的类型相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑下面的代码片段:

  blah :: a  - > b  - > a 
blah x y = ble x其中
ble :: b - > b
ble x = x

这在GHC下编译得很好,其实质上意味着<$第三行的c $ c> b 与第一行的 b 不同。



我的问题很简单:是否有某种方式可以将 ble 的类型声明关联到所使用的类型在外部环境中,即 blah



的类型声明很明显,这只是一个例子而不是

解决方案

这可以通过 ScopedTypeVariables 扩展。你需要使用显式的方法将类型变量放入作用域。

  blah :: forall a b。 a  - > b  - > a 
blah x y = ble x其中
ble :: b - > b
ble x = x

尝试使用ScopedTypeVariables启用加载此定义给出: b>

  foo.hs:2:16:
无法将类型'a'与'b'匹配
`a'是由
绑定的刚性类型变量,用于blah :: a - >的类型签名。 b - > a at foo.hs:2:1
`b'是由
绑定的刚性类型变量,用于blah :: a - >的类型签名。 b - > a在foo.hs:2:1
在`ble'的第一个参数中,即`x'
在表达式中:ble x
在等式`blah'中:
blah xy
= ble x
其中
ble :: b - > b
ble x = x

你可以知道GHC解释了两个<$ c $因为错误表示 a 和 b 是c> b 绑定在同一行上。


Let us consider the following code snippet:

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

This compiles fine under GHC, which essentially means that b from the 3rd line is something different than b from the first line.

My question is simple: is there a way to somehow relate in the type declaration of ble to a type used in an outer context, i.e. the type declaration of blah?

Obviously, this is just an example and not a real-world use-case for type declarations.

解决方案

This is possible with the ScopedTypeVariables extension. You need to use explicit forall's to bring the type variables into scope.

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

Trying to load this definition with ScopedTypeVariables enabled gives:

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

You can tell that GHC interprets the two bs as the same type because the error says that a and b are bound on the same line.

这篇关于如何与来自外部环境的类型相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆