我有一个函数的例子,我不能在where
子句中写一个类型。 replace
是一个函数,它将给定列表中的所有X替换为Y.
replace :: (Eq a) => a -> a -> [a] -> [a]
replace x y xs = map helper xs
where
helper :: (Eq a) => a -> a
helper = (\el -> if el == x then y else el)
当我尝试编译此函数时,出现错误:
ProblemsArithmetics.hs:156:31:
Could not deduce (a ~ a1)
from the context (Eq a)
bound by the type signature for
replace :: Eq a => a -> a -> [a] -> [a]
at ProblemsArithmetics.hs:152:12-41
or from (Eq a1)
bound by the type signature for helper :: Eq a1 => a1 -> a1
at ProblemsArithmetics.hs:155:15-30
‘a’ is a rigid type variable bound by
the type signature for replace :: Eq a => a -> a -> [a] -> [a]
at ProblemsArithmetics.hs:152:12
‘a1’ is a rigid type variable bound by
the type signature for helper :: Eq a1 => a1 -> a1
at ProblemsArithmetics.hs:155:15
Relevant bindings include
el :: a1 (bound at ProblemsArithmetics.hs:156:16)
helper :: a1 -> a1 (bound at ProblemsArithmetics.hs:156:5)
xs :: [a] (bound at ProblemsArithmetics.hs:153:13)
y :: a (bound at ProblemsArithmetics.hs:153:11)
x :: a (bound at ProblemsArithmetics.hs:153:9)
replace :: a -> a -> [a] -> [a]
(bound at ProblemsArithmetics.hs:153:1)
In the second argument of ‘(==)’, namely ‘x’
In the expression: el == x
同时,如果我省略
helper :: (Eq a) => a -> a
代码编译正常。
虽然我理解其背后的逻辑(a
类型声明中的replace
和a
类型声明中的helper
是不同的a
s),并且至少有2个解决方法(省略类型声明或将x
和y
作为helper
函数的参数),我的问题是:
有没有办法告诉编译器我在两种类型声明中的意思相同?
答案 0 :(得分:10)
如果您启用ScopedTypeVariables
并引入带forall
的类型变量,则它会在内部范围内显示。
{-# LANGUAGE ScopedTypeVariables #-}
replace :: forall a. (Eq a) => a -> a -> [a] -> [a]
replace x y xs = map helper xs
where
helper :: a -> a
helper = (\el -> if el == x then y else el)