Pattern matching variables in a case statement in Haskell

被刻印的时光 ゝ 提交于 2019-11-29 06:19:23

See Don's answer for why. A common idiom for doing what you are trying to do is this:

var1 = "abc"
var2 = "def"

foo x = case () of
    () | x == var1 -> "Fail"
       | x == var2 -> "Failzor"
       | otherwise -> "WIN"

Of course in this case we would lose the case and just write the guards directly on the function:

foo x | x == var1 = "Fail"
      | ...

UPDATE

These days the MultiWayIf extension does this with slightly less syntactic noise.

{-# LANGUAGE MultiWayIf #-}

foo x = if | x == var1 -> "Fail"
           | x == var2 -> "Failzor"
           | otherwise -> "WIN"

Pattern matching in Haskell binds new variables. So when you write:

case x of
    y -> ...

you have now bound a new variable 'y' to the value of 'x'. This is the trivial "pattern". You can see more clearly how the binding works when a constructor is involved:

case x of 
    (a, b) -> ...

Now a and b bind to components of the tuple. And so on for deconstructing and binding other data types. Thus, to match a string literal, you would write:

case x of
    "def" -> ....

That's because the "case" isn't doing what you think it is. The "var2" that was set to "def" is not being compared with "var1". Instead you are getting a new scope containing a new "var2" that is bound to the value of "var1".

The reason for the error message is that as far as the compiler is concerned there is no difference between "var2 ->..." and "_ -> ...". Both match all possible values of "var1".

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