Posts Tagged ‘lc’

List comprehensions 另类用法

April 7th, 2010 2 comments

原创文章,转载请注明: 转载自系统技术非业余研究

本文链接地址: List comprehensions 另类用法

List Comprehensions
List comprehensions are a feature of many modern functional programming languages. Subject to certain rules, they provide a succinct notation for generating elements in a list.
List comprehensions are analogous to set comprehensions in Zermelo-Frankel set theory and are called ZF expressions in Miranda. They are analogous to the setof and findall predicates in Prolog.

List comprehensions are written with the following syntax:

[Expr || Qualifier1,…,QualifierN]

Expr is an arbitrary expression, and each Qualifier is either a generator or a filter.

* A generator is written as:
Pattern <- ListExpr. ListExpr must be an expression which evaluates to a list of terms. * A bit string generator is written as: BitstringPattern <= BitStringExpr. BitStringExpr must be an expression which evaluates to a bitstring. * A filter is an expression which evaluates to true or false.

但是从R13B以后lc是可以不要generator的, 只要filter也可以.

root@ubuntu:~# erl
Erlang R13B04 (erts-5.7.5)  [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> Nums = [1,2,3], Nouns = [shoe,box,tape], Verbs = [].
2> [Nums || Nums =/= []] ++ [Nouns || Nouns =/= []] ++ [Verbs || Verbs
=/= []].


Cond = 2,
[io:format("hello~n", []) || Cond =/=1].

免得用if 或者case语句写, 整个代码显得更清爽.

Post Footer automatically generated by wp-posturl plugin for wordpress.

Categories: Erlang探索 Tags: ,