问题描述
我注意到,尝试在带有参数的haskell中执行模式匹配并不总是可行.这是一个示例:
I noticed that trying to perform pattern matching in haskell with the arguments doesn't quite always work. Here's an example:
test :: Integer -> Integer -> String
test num1 num2 = case num1 of
num2 -> "foo"
otherwise -> "bar"
当我将其加载到解释器中时,它会警告我重叠的模式匹配.此外,对于任何两个整数 a
和 b
的 test ab
都会返回"foo"
,无论它们是否是否相等.看来,模式匹配中的 num2
与参数中的 num2
不同.
When I load this in the interpreter, it warns me of overlapping pattern matches. Further more, test a b
for any two integers a
and b
returns "foo"
, regardless of whether they're equal or not. It appears that the num2
in the pattern match is not the same as the one in the arguments.
我想知道为什么会这样.我非常感谢您对此情况有任何见识.
I want to know why exactly this is happening. I'd really appreciate any insight into the situation.
推荐答案
num2
是可与任何值匹配的模式.总是.它与范围内的现有变量 num2
无关.(在大小写替代项的右侧,这里为"foo"
,匹配的值将绑定到名称 num2
,而现有名称为 num2
.但这在这里无关紧要,因为您始终不使用 num2
.)
num2
is a pattern that matches any value. Always. It has nothing to do with an existing variable num2
that is in scope. (In the right-hand side of the case alternative, here "foo"
, the value matched will be bound to the name num2
, shadowing the existing name num2
. But that's not relevant here since you don't use num2
anyways.)
想象一下,如果您所有的 map f(x:xs)= fx:map f xs
模式都匹配,则意味着有人定义了一个名为 x
的顶级变量!
Imagine if all your map f (x : xs) = f x : map f xs
pattern matches changed meaning just because someone defined a top-level variable called x
!
类似地, otherwise
是一种匹配所有内容的模式,与顶级值 otherwise
无关.否则
应该用于类似 |的防护中否则= ...
;它的定义是 otherwise = True
.
Similarly, otherwise
is a pattern that matches everything, and has nothing to do with the top-level value otherwise
. otherwise
is supposed to be used in guards like | otherwise = ...
; its definition is otherwise = True
.
在这种情况下,修复程序的最简单方法就是
In this case, the easiest way to fix your program is just
test num1 num2 = if num1 == num2 then "foo" else "bar"
这篇关于Haskell中的整数与模式匹配给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!