[英]Problems with Haskell variable scope error and creating a proper type declaration
In most of my functions, I seem to get the common error of "Variable not in scope" For example this function在我的大多数函数中,我似乎都收到了“变量不在范围内”的常见错误,例如这个函数
zipmap :: [Int]->[Int]->[Int]
zipmap x y = map (\(a,b) -> a + b) (x zip y)
would give me "Variable not in scope: zipmap :: [Integer] -> [Integer] -> t"会给我“变量不在范围内:zipmap :: [Integer] -> [Integer] -> t”
Why is this happening, and for future reference what can I do to avoid these errors?为什么会发生这种情况,我可以做些什么来避免这些错误,以供将来参考?
My guess is that there are already errors when you define the function.我的猜测是定义函数时已经存在错误。 Since you fail to define the
zipmap
function, the interactive shell assumes nothing happened, and thus it does not know about a function zipmap
later in the process.由于您未能定义
zipmap
函数,交互式 shell 会假设没有发生任何事情,因此在此过程的后期它不知道zipmap
函数。 For example:例如:
$ ghci
GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help
Prelude> zipmap :: [Int]->[Int]->[Int]; zipmap x y = map (\(a,b) -> a + b) (x zip y)
<interactive>:1:68: error: • Couldn't match expected type ‘([a0] -> [b0] -> [(a0, b0)]) -> [Int] -> [(Int, Int)]’ with actual type ‘[Int]’ • The function ‘x’ is applied to two arguments, but its type ‘[Int]’ has none In the second argument of ‘map’, namely ‘(x zip y)’ In the expression: map (\ (a, b) -> a + b) (x zip y)
Prelude> zipmap [1,2,3] [1,4,2,5]
<interactive>:2:1: error:
Variable not in scope: zipmap :: [Integer] -> [Integer] -> t
Note the part in boldface: the interpreter says it does not understand what you say, so it can not proceed with that.注意黑体部分:解释器说它不明白你说的话,所以它不能继续。 Then later if we use
zipmap
, it raises the same error like the one you describe.然后,如果我们使用
zipmap
,它会引发与您描述的相同的错误。
Your zipmap
function is wrong since you write:你的
zipmap
函数是错误的,因为你写了:
x zip y
zip :: [a] -> [b] -> [(a,b)]
is a function, not an operator, so you should use it as: zip :: [a] -> [b] -> [(a,b)]
是一个函数,而不是一个运算符,所以你应该将它用作:
zip x y
Or in full:或全文:
zipmap :: [Int] -> [Int] -> [Int]
zipmap x y = map (\(a,b) -> a + b) (zip x y)
We can further improve this: there is a zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
function:我们可以进一步改进:有一个
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
函数:
zipmap :: [Int] -> [Int] -> [Int]
zipmap x y = zipWith (+) x y
or even shorter:甚至更短:
zipmap :: [Int] -> [Int] -> [Int]
zipmap = zipWith (+)
and finally we can generalize our function:最后我们可以概括我们的功能:
zipmap :: Num a => [a] -> [a] -> [a]
zipmap = zipWith (+)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.