作为 Haskell 学习过程的一部分,我喜欢显式地键入函数的类型声明。我希望能够对 where 子句中定义的函数执行此操作,但我不知道如何指定 where 子句中的类型变量应表示与外部类型声明中的某些类型变量相同的类型。例如,以下代码:
foo :: (a -> a) -> a -> a
foo f arg = bar arg
where
bar :: a -> a
bar a = f a
产生这个错误:
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
我如何表达 bar 的第一个参数应该与 foo 的第二个参数具有相同的类型,以便我可以将 f 应用于它?
Thanks.
我认为你一般可以这样做作用域类型变量 https://downloads.haskell.org/ghc/latest/docs/users_guide/exts/scoped_type_variables.htmlGHC 支持。这肯定可以编译:
{-# LANGUAGE ScopedTypeVariables #-}
foo :: forall a. (a -> a) -> a -> a
foo f arg = bar arg
where
bar :: a -> a
bar a = f a
注意“forall a”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)