如何为 GHCI 强制执行类型构造函数参数

How to enforce a type constructor parameter for GHCI

您好,我遇到了以下问题: 我正在通过一种方法构建参数 newtype,但我不知道如何明确地告诉 GHCII want you to instiantiate this newtype using this type parameter

 newtype M a = M {fu::a->Int}

 var = M (\s-> length (s:"asa"))  #tell him i want the type parameter to be Char

 b = (fu var) 'c' 

我希望得到的是:4 因为 length 'c':"aaa"==4

我得到的是:

interactive>:118:5: error:
    * Couldn't match expected type `A [Char]'
                  with actual type `Ghci30.A [Char]'
      NB: `Ghci30.A' is defined at <interactive>:100:1-25
          `A' is defined at <interactive>:109:1-25
    * In the first argument of `fu', namely `b'
      In the expression: (fu b) "asa"
      In an equation for `it': it = (fu b) "asa"

当您看到像 Ghci30.A [Char] 这样的名称时,这意味着您已经在 GHCi 中重新定义了类型 A。如果您使用正确的 .hs 文件并重新加载它,这将不是问题。

考虑这个 GHCi session:

> data A = A Int
> x = A 2
> data A = A Char  -- redefinition
> :t x

输出应该是什么? x 的类型是 A,但它与内部具有 Char 的类型 A 不同。 GHCi 会将类型打印为

x :: Ghci0.A

如果在重新定义类型 A.

后(重新)定义 x,则不会再次出现错误

如果你的情况,要重新定义的 x 很可能是 fu,它仍然指的是旧的 A。用 :t fu 检查它:如果它提到 Ghci30.A,就是它。

对于重要的定义,我建议使用 .hs 文件并重新加载它,以避免任何麻烦。