Use an if
expression.
(使用if
表达式。)
That's really all guards are anyway: (无论如何,实际上所有警卫都是:)
case x of
_ ->
if x > 10 then
...
else
...
In some cases this does result in duplicate else
branches that could otherwise have been covered by a single _
branch.
(在某些情况下,这确实导致重复的else
分支,否则可能被单个_
分支覆盖。)
The solution to this the same as for code reuse anywhere else though: Use functions: (解决方案与在其他任何地方重复使用代码相同:使用函数:)
let
default = ...
in
case x of
Some y ->
if y > 10 then
...
else
default
_ ->
default
Why was it removed?
(为什么将其删除?)
Well, I can't read Evan's mind any more that you can, but my guess is because it complicates both the syntax and semantics of case
expressions. (好吧,我无法再读懂Evan的想法了,但是我的猜测是因为它使case
表达式的语法和语义都变得复杂。)
For example, a common mistake for beginners is to get confused when the compiler complains that a case
expression isn't exhaustive when they've provided branches with guards that do cover all the cases:
(例如,对于初学者常见的错误是会感到困惑时,编译器会抱怨,一个case
时,他们已经提供分支与做覆盖所有案件后卫表现并不详尽:)
case x of
_ | x < 10 -> ...
_ | x >= 10 -> ...
-- Error: This `case` does not have branches for all possibilities
-- Why u do dis, compiler?
The mix of static patterns with exhaustiveness checking and dynamic guard expressions that can use variables and operators is very confusing to many beginners.
(静态模式与穷举性检查以及可以使用变量和运算符的动态防护表达式的混合使用对许多初学者来说非常令人困惑。)
Many also use case
expressions with guards instead of any if
expression, just because case
"feels more functional". (许多case
还使用带保护的case
表达式,而不是任何 if
表达式,只是因为case
“感觉更实用”。)
Not having guards therefore makes for a language that is much easier to learn and still just as capable, at the cost of being slightly more verbose in some relatively rare cases.
(因此,没有警卫会使语言变得更易于学习,但仍然具有同等的能力,但在某些相对罕见的情况下,语言会变得更加冗长。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…