如何在内部类型声明中重用一个类型变量 [英] How to reuse a type variable in an inner type declaration
问题描述
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屋!