问题描述
我一直试图向几个人解释 switch 语句和模式匹配 (F#) 之间的区别,但我真的无法很好地解释它......大多数时候他们只是看着我说那你为什么不直接使用 if..then..else".
I have been trying to explain the difference between switch statements and pattern matching(F#) to a couple of people but I haven't really been able to explain it well..most of the time they just look at me and say "so why don't you just use if..then..else".
你会如何向他们解释?
编辑!感谢大家的精彩答案,我真的希望我可以标记多个正确的答案.
EDIT! Thanks everyone for the great answers, I really wish I could mark multiple right answers.
推荐答案
我以前是那些人"中的一员,我不知道有没有一种简洁的方式来总结为什么模式匹配是如此美味.这是体验式的.
Having formerly been one of "those people", I don't know that there's a succinct way to sum up why pattern-matching is such tasty goodness. It's experiential.
当我刚刚看到模式匹配并认为它是一个美化的 switch 语句时,我认为我没有使用代数数据类型(元组和可区分联合)进行编程的经验,也不太了解这种模式匹配既是控制结构又是绑定结构.既然我一直在用 F# 编程,我终于明白了".模式匹配的酷炫之处在于函数式编程语言中的各种特性的融合,因此对于局外人来说,欣赏它是非常重要的.
Back when I had just glanced at pattern-matching and thought it was a glorified switch statement, I think that I didn't have experience programming with algebraic data types (tuples and discriminated unions) and didn't quite see that pattern matching was both a control construct and a binding construct. Now that I've been programming with F#, I finally "get it". Pattern-matching's coolness is due to a confluence of features found in functional programming languages, and so it's non-trivial for the outsider-looking-in to appreciate.
在关于语言和 API 设计的由两部分组成的简短博客系列的第二部分中,我试图总结模式匹配为何有用的一个方面;查看第一部分和第二部分.
I tried to sum up one aspect of why pattern-matching is useful in the second of a short two-part blog series on language and API design; check out part one and part two.
这篇关于解释模式匹配与开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!