模式匹配Haskell中的case语句中的变量 [英] Pattern matching variables in a case statement in Haskell
问题描述
如果我使用case语句将一个字符串文字与一个字符串文字进行比较,我会得到预期的行为:如果他们是相同的 - 它匹配,如果不是 - 它不。
If I compare a string literal to a string literal using the case statement, I get the expected behavior: if they are the same - it matches, if they are not - it does not.
但是,如果我把一个字符串字符串和一个字符串的常量比较,我得到模式匹配重叠警告和分支与常量总是匹配。
However, if I compare a string literal to a constant that is a string, I get "Pattern matches are overlapped" warning and the branch with the constant always matches.
这是一个会话示例:
Prelude> let var1 = "abc"
Prelude> let var2 = "def"
Prelude> case var1 of { var2 -> "Fail"; _ -> "Win" }
<interactive>:1:0:
Warning: Pattern match(es) are overlapped
In a case alternative: _ -> ...
"Fail"
Prelude> case "abc" of { var2 -> "Fail"; _ -> "Win" }
<interactive>:1:0:
Warning: Pattern match(es) are overlapped
In a case alternative: _ -> ...
"Fail"
Prelude> case "abc" of { "def" -> "Fail"; _ -> "Win" }
"Win"
>
Meanwhile, if behaves as expected:
> Prelude> if var1 == var2 then "Fail" else "Win"
"Win"
在这里?
推荐答案
请参阅Don的回答为什么。执行你想要做的一个常见的做法是:
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"
当然在这种情况下,我们会失去 code>并直接写上保护程序的函数:
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
这些天, MultiWayIf
扩展会稍微减少语法噪音。
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"
这篇关于模式匹配Haskell中的case语句中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!