Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

pattern-matching - 为什么要从榆树中撤走警卫?(Why were case guards removed from Elm?)

Other functional programming languages have this feature, such as OCaml:

(其他功能性编程语言具有此功能,例如OCaml:)

match x with
| _ when x < 10 -> ...

or Haskell:

(或Haskell:)

case x of 
  _ | x < 10 -> ...

Why was it removed from Elm?

(为什么将其从榆木中移除?)

(Earlier versions had it.)

((早期版本有它。))
What is the idiomatic way to express the same in Elm?

(在榆木中表达相同的惯用方式是什么?)

  ask by ??? translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(因此,没有警卫会使语言变得更易于学习,但仍然具有同等的能力,但在某些相对罕见的情况下,语言会变得更加冗长。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...