相关于my earlier question on traversing data structures ,当我将代码与 uniplate 包一起使用时,我在使代码变得通用时遇到问题。我正在处理 Language.Exts.Annotated.Syntax 中的数据结构模块,它们都是带有类型参数l
的泛型。这个l
在整个树中都是相同的。
我正在编写的代码是这样的:
doInt :: Child1 l -> Child1 l
doInt (Child1 l n) = Child1 l (n + 1)
doString :: Child2 l -> Child2 l
doString (Child2 l (_:s)) = Child2 l ('j' : s)
replace :: Data l => Parent l -> Parent l
replace = transformBi doInt
. transformBi doString
此代码在最后两行都会产生以下错误:
Ambiguous type variable `l' in the constraint: `Data l' arising from a use of `transformBi' at Test.hs:31:10-52 Probable fix: add a type signature that fixes these type variable(s)
我明白为什么这段代码不明确:transformBi
接受(to -> to)
和from
并将其转换为来自
;就我而言,Child1 l
中的 l
和 Parent l
中的 l
之间没有链接。我不知道如何解决它。我尝试添加类似 transformBi (doInt::Child1 l -> Child1 l)
的类型约束,但出现相同的错误;当我这样做时,就好像我正在引入一个新的l
。
如何告诉编译器我对 replace
、transformBi doInt
和 transformBi doString< 使用相同的
?l
/
编辑: Here is the full program that demonstrates what I'm doing 。在GHC 6.10.4下,该程序无法编译,出现上述错误。
最佳答案
看来您需要 scoped type variables扩展名。
{-# LANGUAGE ScopedTypeVariables #-}
replace :: forall l. Data l => Parent l -> Parent l
replace = transformBi (doInt :: Child1 l -> Child1 l)
. transformBi (doString :: Child2 l -> Child2 l)
请注意,量化必须明确才能将l
纳入范围。
关于haskell - 不明确的类型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1865351/