解释模式匹配与切换 [英] Explaining pattern matching vs switch

查看:82
本文介绍了解释模式匹配与切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图向几个人解释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".

您将如何向他们解释?

How would you explain it to them?

编辑!谢谢大家的出色回答,我真的希望我能为多个正确答案做出标记.

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.

这篇关于解释模式匹配与切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆