【问题标题】:How to reference an already existing type variable in a haskell type spec?如何在 haskell 类型规范中引用已经存在的类型变量?
【发布时间】:2013-08-21 06:07:57
【问题描述】:

我希望在函数 f 中定义一个函数 f',以便它们的两个类型规范都引用同一个类型变量。但是,当我尝试这样做时,我从编译器中得到一个编译错误,它假定外部的 m 和内部的 m 不是同一个类型变量。有关如何解决此问题的任何提示?

f :: (Monad m) => (String -> Int -> String -> m ()) -> [String] -> m () 
f _ (x:_) = f' Nothing x
  where 
    f' :: (Maybe Int) -> String -> m () -- when I comment this line, the code compiles
    f' _ _ = return ()

main = undefined

【问题讨论】:

  • 谢谢,这解决了。如果您将其更改为答案,我会将其标记为正确。
  • 对于这个特定的示例,您还可以通过在内部类型签名中添加(Monad m) 约束来编译它。
  • 您能否在您的问题中始终包含full error messages。 :) 如果你看那里,你会发现 GHC 实际上提出了与上面 Gabriel Gonzalez 评论中相同的修复方法。

标签: haskell types generic-programming strong-typing


【解决方案1】:

查看http://www.haskell.org/haskellwiki/Scoped_type_variables

从链接: Scoped Type Variables are an extension to Haskell's type system that allow free type variables to be re-used in the scope of a function.

【讨论】:

    【解决方案2】:

    Haskell 98 Prelude 还包含一个函数asTypeOf,它可用于在一定程度上模拟作用域类型变量(如果您使用不支持 XScopedTypeVariables 的编译器)。

    http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:asTypeOf

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      相关资源
      最近更新 更多