haskell - 如何与外部上下文中的类型相关联

标签 haskell types functional-programming ghc type-declaration

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

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 为同一类型,因为错误表明 ab绑定(bind)在同一条线上。

关于haskell - 如何与外部上下文中的类型相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8400150/

相关文章:

swift 。我如何获得 node.children 的类型?

c - C const 的默认类型是什么?

c# - 逆 .ToString()

function - 函数算术?

haskell - 如何强制 Haskell 检查列表的长度?

haskell - 如何从 yesod 中的 PersistObjectId 获取字符串?

scala - 混合面向对象和函数式编程

scala - 掌握不可变数据结构

多参数函数的 Haskell 类型声明

haskell - 如何在 Haskell 中创建异构列表? (最初在 Java 中)