如何在内部类型声明中重用一个类型变量 [英] How to reuse a type variable in an inner type declaration

查看:101
本文介绍了如何在内部类型声明中重用一个类型变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为Haskell学习过程的一部分,我喜欢明确地输出函数的类型声明。我希望能够为where子句中定义的函数执行此操作,但我不知道如何指定where子句中的类型变量应表示与外部类型声明中的某个类型变量相同的类型。例如,以下代码:

  foo ::(a  - > a) - > a  - > a 
foo f arg = bar arg
其中
bar :: a - > a
a = fa

会产生这个错误:

  src\Test.hs:7:14:
无法匹配预期的类型'a'与推断的类型'a1'
`a'是一个由$ b $b绑定的刚性类型变量,src\Test.hs:3:8处的`foo'的类型签名
`a1'是一个刚性类型变量,由
src\Test.hs:6:11
处的`bar'类型签名在`f'的第一个参数中,即`a'
在表达式中:fa
在bar'的定义:bar a = fa

如何表达bar的第一个参数应该与foo的第二个参数的类型相同,这样我就可以将f应用于它了?



谢谢。

解决方案

我认为你可以通过 ScopedTypeVari这是GHC支持的。这肯定会编译:

  { - #LANGUAGE ScopedTypeVariables# - } 
foo :: forall a。 (a - > a) - > a - > a
foo f arg = bar arg
其中
bar :: a - > a
a = fa

请注意forall a。


As part of my Haskell learning process, I like to explicitly type out the type declarations for functions. I would like to be able to do so for functions defined in a where clause, but I don't know how to specify, that a type variable in a where clause should denote the same type as some type variable in the outer type declaration. For instance, the following code:

foo :: (a -> a) -> a -> a
foo f arg = bar arg
  where
    bar :: a -> a
    bar a = f a

yields this error:

src\Test.hs:7:14:
    Couldn't match expected type `a' against inferred type `a1'
      `a' is a rigid type variable bound by
          the type signature for `foo' at src\Test.hs:3:8
      `a1' is a rigid type variable bound by
           the type signature for `bar' at src\Test.hs:6:11
    In the first argument of `f', namely `a'
    In the expression: f a
    In the definition of `bar': bar a = f a

How can I express that the first argument to bar should be of the same type as the second argument to foo, so that I can apply f to it?

Thanks.

解决方案

I think you can do this in general with ScopedTypeVariables which GHC supports. This certainly compiles:

{-# LANGUAGE ScopedTypeVariables #-}
foo :: forall a. (a -> a) -> a -> a
foo f arg = bar arg
  where
    bar :: a -> a
    bar a = f a

Note the "forall a."

这篇关于如何在内部类型声明中重用一个类型变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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