CoffeeScript 中的模式匹配

发布于 2024-12-05 05:19:19 字数 173 浏览 1 评论 0原文

除了这些例子之外,我正在努力寻找咖啡脚本和模式匹配的任何好的例子:

{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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撩心不撩汉 2024-12-12 05:19:19

啊,我想我认识这些例子: http://pragprog.com/magazines/ 2011-05/a-coffeescript-intervention :)

CoffeeScript 的模式匹配(更正式地称为“解构赋值”,以区别于 Erland 中的模式匹配)和 Scala,这是完全不同的)可用于从非常复杂的数据结构中提取信息。这是来自 官方文档 的示例:

{poet: {name, address: [street, city]}} = futurists

它基本上等同于

poet = futurists.poet
name = poet.name
street = poet.address[0]
city = poet.address[1]

但实际上, ,解构赋值主要用于获取一两个对象属性,如您提到的示例,或者用于从数组中获取部分。例如,您可以通过编写交换两个变量 ab 的值

[a, b] = [b, a]

,并且使用 splats,您可以获得数组 arr 的第一个和最后一个值 通过写作

[first, middle..., last] = 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:

{poet: {name, address: [street, city]}} = futurists

which is essentially equivalent to

poet = futurists.poet
name = poet.name
street = poet.address[0]
city = poet.address[1]

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 and b by writing

[a, b] = [b, a]

and, using splats, you can get the first and last values of an array arr by writing

[first, middle..., last] = arr

I hope that helps. There are of course more examples in my book, CoffeeScript: Accelerated JavaScript Development.

梦初启 2024-12-12 05:19:19

有一个库提供了一种在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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文