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

时间:2018-11-05 10:08:59

标签: haskell type-parameter type-constructor

你好,我有以下问题: 我正在通过一种方法构造参数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"

1 个答案:

答案 0 :(得分:3)

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

考虑此GHCi会话:

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

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

x :: Ghci0.A

如果您在重新定义类型x后重新定义A,将不会再收到错误消息。

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

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