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

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

问题描述

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

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

产生此错误:

srcTest.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 srcTest.hs:3:8
      `a1' is a rigid type variable bound by
           the type signature for `bar' at srcTest.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

如何表示 bar 的第一个参数应该与 foo 的第二个参数类型相同,以便我可以对其应用 f?

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?

谢谢.

推荐答案

我认为您通常可以使用 ScopedTypeVariables.这当然可以编译:

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

注意forall a".

Note the "forall a."

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

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