Pattern matching with integer in haskell gives wrong result

此生再无相见时 提交于 2019-12-13 05:26:40

问题


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"

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.


回答1:


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.)

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!

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"


来源:https://stackoverflow.com/questions/34438797/pattern-matching-with-integer-in-haskell-gives-wrong-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!