Erlang,列表理解语法
我在 Erlang 中看到了这段代码:
[X-$0 || X<-someFun()]
在那一行中我发现 -$0
语法非常有用。
我阅读了代码并估计了它的含义,但我不太确定:它是否拆分了所有数字?
我想查看该语法的解释或手册页,但找不到。 谁能告诉我正确的页面吗?
I saw this code in Erlang:
[X-$0 || X<-someFun()]
In that line I found the -$0
syntax very useful.
I read the code and estimated what it means, but I'm not quite sure: is it split all numbers?
I'd like to see the explanation or man page of that syntax but I can't find it. Can anyone show me the right page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该代码所做的是从
someFun()
获取输出(需要返回一个列表),并且对于列表中的每个元素,它将元素的值分配给变量X< /code>,然后从该值中减去字符
0
的 ASCII 值。 结果列表就是整个表达式的值。在实践中(我自己已经编写了数十次此代码),它所做的事情是假设
someFun/0
是一个返回仅包含数字的字符串的函数,然后将其转换将字符串转换为数字列表。 因此,如果someFun()
返回“12345
”,则此列表理解的结果为[1, 2, 3, 4, 5]
。如果您熟悉
map
函数(如 MapReduce)的概念,那么现在这听起来应该非常熟悉。这个 wikibooks 页面看起来像是对 Erlang 列表推导式的一个很好的介绍:
http://en.wikibooks.org/ wiki/Erlang_Programming/List_Compressives
Joe Armstrong 的书《Programming Erlang》,来自 Pragmatic 书架,( http://pragprog.com/titles/jaerlang/programming-erlang)也很好地涵盖了列表推导式(以及与 Erlang 相关的其他所有内容)。 优秀的书,强烈推荐等等。
What that code is doing is taking the output from
someFun()
(which needs to return a list), and for each element in the list it is assigning the element's value to the variableX
and then subtracting the ASCII value of the character0
from that value. The resulting list is then the value of that whole expression.What it's doing, in practice (and I've written this code dozens of times myself), is assuming that
someFun/0
is a function that returns a string with just digits in it, and then converting that string into a list of the digits. So, ifsomeFun()
returned "12345
", the result of this list comprehension is[1, 2, 3, 4, 5]
.If you're familiar with the concept of a
map
function (as in, MapReduce), then this should be sounding pretty familiar by now.This wikibooks page looks like a good introduction to Erlang list comprehensions:
http://en.wikibooks.org/wiki/Erlang_Programming/List_Comprehensions
Joe Armstrong's book "Programming Erlang", from the Pragmatic Bookshelf, (http://pragprog.com/titles/jaerlang/programming-erlang) also covers list comprehensions really well (along with everything else Erlang related). Excellent book, highly recommended, etc.
列表推导式的常规文档页面位于 Erlang 参考手册第 6.22 节和在 编程示例第 3 节中。
这两个内容都在 主文档页面(单击左侧菜单栏上的 Erlang 编程文件夹)。
Erlang 文档很棒 - 只是它的布局有点简陋......
The normal documentation page for list comprehensions is in the Erlang Reference Manual Section 6.22 and in Programming Examples Section 3.
Both of these are on the main documentation page (click on the Erlang Programming Folder on the left hand menu bar).
The Erlang documentation is fab - it's just its layout is a tad shonky...