CoffeeScript 中的模式匹配
除了这些例子之外,我正在努力寻找咖啡脚本和模式匹配的任何好的例子:
{x, y} = sprite
css = {opacity, fontFamily}
我在 Erlang 中使用了模式匹配,但我正在努力在咖啡脚本中寻找一些更高级的例子来准确地说明什么是可能的。
I am struggling with finding any good examples of coffeescript and pattern matching apart from these sort of examples:
{x, y} = sprite
css = {opacity, fontFamily}
I have used pattern matching in Erlang but I am struggling with finding some more advanced examples in coffeescript which illustrate exactly what is possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
啊,我想我认识这些例子: http://pragprog.com/magazines/ 2011-05/a-coffeescript-intervention :)
CoffeeScript 的模式匹配(更正式地称为“解构赋值”,以区别于 Erland 中的模式匹配)和 Scala,这是完全不同的)可用于从非常复杂的数据结构中提取信息。这是来自 官方文档 的示例:
它基本上等同于
但实际上, ,解构赋值主要用于获取一两个对象属性,如您提到的示例,或者用于从数组中获取部分。例如,您可以通过编写交换两个变量
a
和b
的值,并且使用 splats,您可以获得数组
arr 的第一个和最后一个值
通过写作我希望有所帮助。当然,我的书中还有更多示例,CoffeeScript:加速 JavaScript 开发。
Ah, I thought I recognized those examples: http://pragprog.com/magazines/2011-05/a-coffeescript-intervention :)
CoffeeScript's pattern-matching (more formally called "destructuring assignment" to distinguish it from pattern-matching in Erland and Scala, which is quite different) can be used to extract information from very elaborate data structures. Here's an example from the official docs:
which is essentially equivalent to
In practice, though, destructuring assignment is mainly used for grabbing one or two object properties, as in the examples you mentioned, or for getting parts from an array. For instance, you can swap the values of two variables
a
andb
by writingand, using splats, you can get the first and last values of an array
arr
by writingI hope that helps. There are of course more examples in my book, CoffeeScript: Accelerated JavaScript Development.
有一个库提供了一种在coffeescript中编写类似Erlang的结构的方法,无需预编译,只需将其包装在特殊函数中即可。您可以在这里找到它:https://github.com/nogizhopaboroda/f_context。
There is a a library which provides a way to write Erlang-like constructions right in coffeescript without precompilation, just wrap up it in special function. You can find it here: https://github.com/nogizhopaboroda/f_context.