[英]Haskell: Type declaration in `where`
I have an example of function, in which I can't write a type in where
clause. 我有一个函数的例子,其中我不能在where
子句中写一个类型。 replace
is a function, that replaces all Xs by Ys in a given list. 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)
When I try to compile this function I get an error: 当我尝试编译此函数时,我收到一个错误:
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
At the same time, if I omit 同时,如果我省略
helper :: (Eq a) => a -> a
the code is compiled fine. 代码编译得很好。
While I understand the logic behind it ( a
in replace
type declaration and a
in helper
type declaration are different a
s), and there are at least 2 workarounds (omit type declaration or pass x
and y
as parameters to helper
function), my question is: 虽然我理解它背后的逻辑( a
在replace
类型声明和a
在helper
类型声明是不同的a
或多个),和至少有2解决方法(省略类型声明或通过x
和y
作为参数helper
功能),我的问题是:
Is there any way to tell the compiler that I mean the same type in both type declarations? 有没有办法告诉编译器我的意思是两种类型声明中的相同类型?
If you enable ScopedTypeVariables
and introduce a type variable with a forall
, then it becomes visible in the inner scope. 如果启用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.