https://en.wikipedia.org/w/api.php?action=feedcontributions&feedformat=atom&user=147.251.229.23Wikipedia - User contributions [en]2024-11-08T22:09:24ZUser contributionsMediaWiki 1.44.0-wmf.2https://en.wikipedia.org/w/index.php?title=List_comprehension&diff=805422304List comprehension2017-10-15T08:24:50Z<p>147.251.229.23: /* C++ */ do not return references to local variables</p>
<hr />
<div>A '''list comprehension''' is a [[Syntax of programming languages|syntactic]] construct available in some [[programming language]]s for creating a list based on existing [[list (computing)|lists]]. It follows the form of the mathematical ''[[set-builder notation]]'' (''set comprehension'') as distinct from the use of [[Map (higher-order function)|map]] and [[Filter (higher-order function)|filter]] functions.<br />
<br />
==Overview==<br />
Consider the following example in [[set-builder notation]].<br />
<br />
:<math>S=\{\,2\cdot x\mid x \in \mathbb{N},\ x^2>3\,\}</math><br />
<br />
This can be read, "<math>S</math> is the set of all numbers "2 times <math>x</math>" where <math>x</math> is an item in the set of [[natural number]]s (<math>\mathbb{N}</math>), for which <math>x</math> squared is greater than <math>3</math>."<br />
<br />
The smallest natural number, x = 1, fails to satisfy the condition x<sup>2</sup>>3 (the condition 1<sup>2</sup>>3 is false) so 2 ·1 is not included in S. The next natural number, 2, does satisfy the condition (2<sup>2</sup>>3) as does every other natural number. Thus S consists of 2 ·2, 2 ·3, 2 ·4... so S = 4, 6, 8, 10,... i.e., all even numbers greater than 2.<br />
<br />
In this annotated version of the example:<br />
:<math>S=\{\,\underbrace{2\cdot x}_{\color{Violet}{\text{output expression}}}\mid \underbrace{x}_{\color{Violet}{\text{variable}}} \in \underbrace{\mathbb{N}}_{\color{Violet}{\text{input set}}},\ \underbrace{x^2>3}_{\color{Violet}{\text{predicate}}}\,\}</math><br />
* <math>x</math> is the variable representing members of an input set.<br />
* <math>\mathbb{N}</math> represents the input set, which in this example is the set of natural numbers<br />
* <math>x^2>3</math> is a [[Predicate (logic)|predicate]] expression acting as a filter on members of the input set.<br />
* <math>2\cdot x</math> is an output expression producing members of the new set from members of the input set that satisfy the predicate expression.<br />
* <math>\{\}</math> braces indicate that the result is a set<br />
* <math>\mid</math> <math>,</math> the vertical bar and the comma are separators.<br />
<br />
A list comprehension has the same syntactic components to represent generation of a list in order from an input [[List (computing)|list]] or [[iterator]]:<br />
* A variable representing members of an input list.<br />
* An input list (or iterator).<br />
* An optional predicate expression.<br />
* And an output expression producing members of the output list from members of the input iterable that satisfy the predicate.<br />
The order of generation of members of the output list is based on the order of items in the input.<br />
<br />
In [[Haskell (programming language)|Haskell's]] list comprehension syntax, this set-builder construct would be written similarly, as:<br />
<source lang="haskell"><br />
s = [ 2*x | x <- [0..], x^2 > 3 ]<br />
</source><br />
<br />
Here, the list <code>[0..]</code> represents <math>\mathbb{N}</math>, <code>x^2>3</code> represents the predicate, and <code>2*x</code> represents the output expression.<br />
<br />
List comprehensions give results in a defined order (unlike the members of sets); and list comprehensions may [[Generator (computer science)|generate]] the members of a list in order, rather than produce the entirety of the list thus allowing, for example, the previous Haskell definition of the members of an infinite list.<br />
<br />
==History==<br />
<br />
The [[SETL]] programming language (1969) has a set formation construct which is similar to list comprehensions. This code prints all prime numbers from 2 to N:<br />
print([n in [2..N] | forall m in {2..n - 1} | n mod m > 0]);<br />
The [[computer algebra system]] [[Axiom (computer algebra system)|AXIOM]] (1973) has a similar construct that processes [[stream (computing)|stream]]s, but the first use of the term "comprehension" for such constructs was in Rod Burstall and John Darlington's description of their functional programming language [[NPL programming language|NPL]] from 1977.<br />
<br />
[[Smalltalk]] block context messages which constitute list comprehensions have been in that language since at least Smalltalk-80.<br />
<br />
Burstall and Darlington's work with NPL influenced many functional programming languages during the 1980s, but not all included list comprehensions. An exception was the influential pure lazy functional programming language [[Miranda programming language|Miranda]], which was released in 1985. The subsequently developed standard pure lazy functional language [[Haskell programming language|Haskell]] includes many of Miranda's features, including list comprehensions.<br />
<br />
Comprehensions were proposed as a query notation for databases<ref>[http://portal.acm.org/citation.cfm?coll=GUIDE&dl=GUIDE&id=135271 Comprehensions, a query notation for DBPLs<!-- Bot generated title -->]</ref> and were implemented in the ''Kleisli'' database query language.<ref>[http://portal.acm.org/citation.cfm?id=351241&dl=ACM&coll=portal The functional guts of the Kleisli query system<!-- Bot generated title -->]</ref><br />
<br />
== Examples in different programming languages ==<br />
<br />
{{main article|Comparison of programming languages (list comprehension)}}<br />
<br />
==Similar constructs==<br />
<br />
===Monad comprehension===<br />
In Haskell, a [[monads in functional programming#do-notation|monad comprehension]] is a generalization of the list comprehension to other [[monads in functional programming]].<br />
<br />
===Set comprehension===<br />
Version 3.x and 2.7 of the Python language introduces syntax for [[set (computer science)|set]] comprehensions. Similar in form to list comprehensions, set comprehensions generate Python sets instead of lists.<br />
<source lang="python"><br />
>>> s = {v for v in 'ABCDABCD' if v not in 'CB'}<br />
>>> print(s)<br />
{'A', 'D'}<br />
>>> type(s)<br />
<class 'set'><br />
>>> <br />
</source><br />
<br />
[[Racket (programming language)|Racket]] set comprehensions generate Racket sets instead of lists.<br />
<source lang="scheme"><br />
(for/set ([v "ABCDABCD"] #:unless (member v (string->list "CB")))<br />
v))<br />
</source><br />
<br />
===Dictionary comprehension===<br />
Version 3.x and 2.7 of the Python language introduced a new syntax for [[associative array|dictionary]] comprehensions, similar in form to list comprehensions but which generate Python [https://docs.python.org/library/stdtypes.html#dict dicts] instead of lists.<br />
<source lang="python"><br />
>>> s = {key: val for key, val in enumerate('ABCD') if val not in 'CB'}<br />
>>> s<br />
{0: 'A', 3: 'D'}<br />
>>> <br />
</source><br />
<br />
Racket hash table comprehensions generate Racket hash tables (one implementation of the Racket dictionary type).<br />
<source lang="scheme"><br />
(for/hash ([(val key) (in-indexed "ABCD")]<br />
#:unless (member val (string->list "CB")))<br />
(values key val))<br />
</source><br />
<br />
===Parallel list comprehension===<br />
The [[Glasgow Haskell Compiler]] has an extension called '''parallel list comprehension''' (also known as '''zip-comprehension''') that permits multiple independent branches of qualifiers within the list comprehension syntax.<br />
Whereas qualifiers separated by commas are dependent ("nested"), qualifier branches separated by pipes are evaluated in parallel (this does not refer to any form of multithreadedness: it merely means that the branches are [[Map (higher-order function)|zipped]]).<br />
<source lang="haskell"><br />
-- regular list comprehension<br />
a = [(x,y) | x <- [1..5], y <- [3..5]]<br />
-- [(1,3),(1,4),(1,5),(2,3),(2,4) ...<br />
<br />
-- zipped list comprehension<br />
b = [(x,y) | (x,y) <- zip [1..5] [3..5]]<br />
-- [(1,3),(2,4),(3,5)]<br />
<br />
-- parallel list comprehension<br />
c = [(x,y) | x <- [1..5] | y <- [3..5]]<br />
-- [(1,3),(2,4),(3,5)]<br />
</source><br />
<br />
Racket's comprehensions standard library contains parallel and nested versions of its comprehensions, distinguished by "for" vs "for*" in the name. For example, the vector comprehensions "for/vector" and "for*/vector" create vectors by parallel versus nested iteration over sequences. The following is Racket code for the Haskell list comprehension examples.<br />
<source lang="scheme"><br />
> (for*/list ([x (in-range 1 6)] [y (in-range 3 6)]) (list x y))<br />
'((1 3) (1 4) (1 5) (2 3) (2 4) (2 5) (3 3) (3 4) (3 5) (4 3) (4 4) (4 5) (5 3) (5 4) (5 5))<br />
> (for/list ([x (in-range 1 6)] [y (in-range 3 6)]) (list x y))<br />
'((1 3) (2 4) (3 5))<br />
</source><br />
<br />
In Python we could do as follows:<br />
<source lang="python"><br />
# regular list comprehension<br />
>>> a = [(x, y) for x in range(1, 6) for y in range(3, 6)]<br />
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), ...<br />
<br />
# parallel/zipped list comprehension<br />
>>> b = [x for x in zip(range(1, 6), range(3, 6))]<br />
[(1, 3), (2, 4), (3, 5)]<br />
</source><br />
<br />
=== XQuery and XPath ===<br />
Like the original NPL use, these are fundamentally database access languages.<br />
<br />
This makes the comprehension concept more important, because it is computationally infeasible to retrieve the entire list and operate on it (the initial 'entire list' may be an entire XML database).<br />
<br />
In XPath, the expression:<br />
<source lang="xquery"><br />
/library/book//paragraph[@style='first-in-chapter']<br />
</source><br />
is conceptually evaluated as a series of "steps" where each step produces a list and the next step applies a filter function to each element in the previous step's output.<ref>{{cite web | url = http://www.w3.org/TR/xpath#section-Location-Steps | title = 2.1 Location Steps | work = XML Path Language (XPath) | date = 16 November 1999 | publisher = [[W3C]]}}</ref><br />
<br />
In XQuery, full XPath is available, but [[FLWOR]] statements are also used, which is a more powerful comprehension construct.<ref>{{cite web | url = http://www.w3schools.com/XQuery/xquery_flwor.asp | title = XQuery FLWOR Expressions | work = [[W3Schools]]}}</ref><br />
<source lang="xquery"><br />
for $b in //book<br />
where $b[@pages < 400]<br />
order by $b//title<br />
return<br />
<shortBook><br />
<title>{$b//title}</title><br />
<firstPara>{($book//paragraph)[1]}</firstPara><br />
</shortBook><br />
</source><br />
Here the XPath //book is evaluated to create a sequence (aka list); the where clause is a functional "filter", the order by sorts the result, and the {{tag|shortBook}} XML snippet is actually an anonymous function that builds/transforms XML for each element in the sequence using the 'map' approach found in other functional languages.<br />
<br />
So, in another functional language the above FLWOR statement may be implemented like this:<br />
<source lang="xquery"><br />
map(<br />
newXML(shortBook, newXML(title, $1.title), newXML(firstPara, $1...))<br />
filter(<br />
lt($1.pages, 400),<br />
xpath(//book)<br />
)<br />
)<br />
</source><br />
<br />
=== LINQ in C# ===<br />
<br />
[[C Sharp (programming language)|C#]] 3.0 has a group of related features called [[LINQ]], which defines a set of query operators for manipulating object enumerations.<br />
<br />
<source lang="csharp"><br />
var s = Enumerable.Range(0, 100).Where(x => x*x > 3).Select(x => x*2);<br />
</source><br />
<br />
It also offers an alternative comprehension syntax, reminiscent of SQL:<br />
<br />
<source lang="csharp"><br />
var s = from x in Enumerable.Range(0, 100) where x*x > 3 select x*2;<br />
</source><br />
<br />
LINQ provides a capability over typical List Comprehension implementations. When the root object of the comprehension implements the IQueryable interface, rather than just executing the chained methods of the comprehension, the entire sequence of commands are converted into an Abstract Syntax Tree (AST) object, which is passed to the IQueryable object to interpret and execute.<br />
<br />
This allows, amongst other things, for the IQueryable to <br />
* rewrite an incompatible or inefficient comprehension<br />
* translate the AST into another query language (e.g. SQL) for execution<br />
<br />
=== C++ ===<br />
C++ does not have any language features directly supporting list comprehensions but [[operator overloading]] (e.g., overloading |, >>, >>=) has been used successfully to provide expressive syntax for "embedded" query [[Domain-specific language|DSL]]s. Alternatively, list comprehensions can be constructed using the [[erase-remove idiom]] to select elements in a container and the STL algorithm for_each to transform them.<br />
<source lang="cpp"><br />
#include <algorithm><br />
#include <list><br />
#include <numeric><br />
<br />
using namespace std;<br />
<br />
template<class C, class P, class T><br />
C comprehend(C&& source, const P& predicate, const T& transformation)<br />
{<br />
// initialize destination<br />
C d = forward<C>(source);<br />
<br />
// filter elements<br />
d.erase(remove_if(begin(d), end(d), predicate), end(d));<br />
<br />
// apply transformation<br />
for_each(begin(d), end(d), transformation);<br />
<br />
return d;<br />
}<br />
<br />
int main()<br />
{<br />
list<int> range(10); <br />
// range is a list of 10 elements, all zero<br />
iota(begin(range), end(range), 1);<br />
// range now contains 1,2,...,10<br />
<br />
list<int> result = comprehend(<br />
range,<br />
[](int x){return x*x <= 3;},<br />
[](int &x){x *= 2;});<br />
// result now contains 4,6,...,20<br />
}<br />
</source><br />
There is some effort in providing C++ with list-comprehension constructs/syntax similar to the set builder notation.<br />
* In [[Boost C++ Libraries|Boost]].Range [http://www.boost.org/libs/range] library there is a notion of adaptors [http://www.boost.org/libs/range/doc/html/range/reference/adaptors.html] that can be applied to any range and do filtering, transformation etc. With this library, the original Haskell example would look like (using Boost.Lambda [http://www.boost.org/libs/lambda] for anonymous filtering and transforming functions) ([http://codepad.org/y4bpgLJu Full example]):<source lang="cpp"><br />
counting_range(1,10) | filtered( _1*_1 > 3 ) | transformed(ret<int>( _1*2 ))<br />
</source><br />
* This<ref>{{cite web | url = http://mfoliveira.org/blog/2011/01/04/simple-list-comprehension-in-cp-using-preprocessor-macros/ | title = Single-variable List Comprehension in C++ using Preprocessor Macros}}</ref> implementation uses a macro and overloads the << operator. It evaluates any expression valid inside an 'if', and any variable name may be chosen. It's not [[thread safety|threadsafe]], however. Usage example:<source lang="cpp"><br />
list<int> N;<br />
list<double> S;<br />
<br />
for (int i = 0; i < 10; i++)<br />
N.push_back(i);<br />
<br />
S << list_comprehension(3.1415 * x, x, N, x*x > 3)<br />
</source><br />
* This<ref>{{cite web | url = http://www.tedunangst.com/listcc.html | title = C++ list comprehensions}}</ref> implementation provides head/tail slicing using classes and operator overloading, and the | operator for filtering lists (using functions). Usage example:<source lang="cpp"><br />
bool even(int x) { return x % 2 == 0; }<br />
bool x2(int &x) { x *= 2; return true; }<br />
<br />
list<int> l, t;<br />
int x, y;<br />
<br />
for (int i = 0; i < 10; i++)<br />
l.push_back(i);<br />
<br />
(x, t) = l | x2;<br />
(t, y) = t;<br />
<br />
t = l < 9;<br />
t = t < 7 | even | x2;<br />
</source><br />
* Language for Embedded Query and Traversal (LEESA<ref>{{cite web | url = http://www.dre.vanderbilt.edu/LEESA/ | title = Language for Embedded Query and Traversal (LEESA)}}</ref>) is an embedded DSL in C++ that implements X-Path-like queries using operator overloading. The queries are executed on richly typed xml trees obtained using xml-to-c++ binding from an XSD. There is absolutely no string encoding. Even the names of the xml tags are classes and therefore, there is no way for typos. If a LEESA expression forms an incorrect path that does not exist in the data model, the C++ compiler will reject the code.<br>Consider a catalog xml.<source lang="xml"><br />
<catalog><br />
<book><br />
<title>Hamlet</title><br />
<price>9.99</price><br />
<author><br />
<name>William Shakespeare</name><br />
<country>England</country><br />
</author><br />
</book><br />
<book>...</book><br />
...<br />
</catalog><br />
</source><br />
LEESA provides >> for X-Path's / separator. Interestingly, X-Path's // separator that "skips" intermediate nodes in the tree is implemented in LEESA using what's known as Strategic Programming. In the example below, catalog_, book_, author_, and name_ are instances of catalog, book, author, and name classes, respectively.<br />
<source lang="cpp"><br />
// Equivalent X-Path: "catalog/book/author/name"<br />
std::vector<name> author_names = <br />
evaluate(root, catalog_ >> book_ >> author_ >> name_);<br />
<br />
// Equivalent X-Path: "catalog//name"<br />
std::vector<name> author_names = <br />
evaluate(root, catalog_ >> DescendantsOf(catalog_, name_));<br />
<br />
// Equivalent X-Path: "catalog//author[country=="England"]"<br />
std::vector<name> author_names = <br />
evaluate(root, catalog_ >> DescendantsOf(catalog_, author_)<br />
>> Select(author_, [](const author & a) { return a.country()=="England"; })<br />
>> name_);<br />
</source><br />
<br />
==See also==<br />
*The [[Select (SQL)|SELECT]] statement together with its FROM and WHERE clauses in [[SQL#Queries|SQL]]<br />
<br />
==Notes and references==<br />
{{reflist}}<br />
*[http://ftp.sunet.se/foldoc/foldoc.cgi?list+comprehension List Comprehension] in The Free On-line Dictionary of Computing, Editor Denis Howe.<br />
*{{cite conference | first = Phil | last = Trinder | url = http://portal.acm.org/citation.cfm?coll=GUIDE&dl=GUIDE&id=135271 | title = Comprehensions, a query notation for DBPLs | booktitle = Proceedings of the third international workshop on Database programming languages: bulk types & persistent data, Nafplion, Greece | pages = 55–68 | year = 1992}}<br />
*{{cite conference | first = Philip | last = Wadler |url = http://citeseer.ist.psu.edu/wadler92comprehending.html | title = Comprehending Monads | booktitle = Proceedings of the 1990 ACM Conference on LISP and Functional Programming, Nice | year = 1990}}<br />
*{{cite conference | first = Limsoon | last = Wong | url = http://portal.acm.org/citation.cfm?id=351241&dl=ACM&coll=portal | title = The Functional Guts of the Kleisli Query System | conference = International Conference on Functional Programming | booktitle = Proceedings of the fifth ACM SIGPLAN international conference on Functional programming | pages = 1–10 | year = 2000}}<br />
<br />
===Haskell===<br />
*The Haskell 98 Report, chapter [http://haskell.org/onlinereport/exps.html#list-comprehensions 3.11 List Comprehensions].<br />
*The Glorious Glasgow Haskell Compilation System User's Guide, chapter [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#parallel-list-comprehensions 7.3.4 Parallel List Comprehensions].<br />
*The Hugs 98 User's Guide, chapter [http://cvs.haskell.org/Hugs/pages/users_guide/hugs-ghc.html#ZIP-COMPREHENSION 5.1.2 Parallel list comprehensions (a.k.a. zip-comprehensions)].<br />
<br />
===OCaml===<br />
* [http://batteries.forge.ocamlcore.org/ OCaml Batteries Included]<br />
* [http://batteries.forge.ocamlcore.org/doc.preview:batteries-alpha3/html/extensions.html Language extensions introduced in OCaml Batteries Included]<br />
<br />
===Python===<br />
* The Python Tutorial, [https://docs.python.org/tutorial/datastructures.html#list-comprehensions List Comprehensions].<br />
* Python Language Reference, [https://docs.python.org/reference/expressions.html#list-displays List displays].<br />
* Python Enhancement Proposal [https://www.python.org/peps/pep-0202.html PEP 202: List Comprehensions].<br />
* Python Language Reference, [https://docs.python.org/reference/expressions.html#generator-expressions Generator expressions].<br />
* Python Enhancement Proposal [https://python.org/peps/pep-0289.html PEP 289: Generator Expressions].<br />
<br />
===Common Lisp===<br />
* [http://rali.iro.umontreal.ca/Publications/urls/LapalmeLispComp.pdf Implementation of a Lisp comprehension macro] by Guy Lapalme<br />
<br />
===Clojure===<br />
* [https://clojuredocs.org/clojure.core/for Clojure API documentation - ''for'' macro]<br />
<br />
===Axiom===<br />
* [http://page.axiom-developer.org/zope/mathaction/Streams Axiom stream examples]<br />
<br />
==External links==<br />
* SQL-like set operations with list comprehension one-liners in the [http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159974 Python Cookbook]<br />
* [http://lambda-the-ultimate.org/classic/message11326.html Discussion on list comprehensions in Scheme and related constructs]<br />
* [http://langexplr.blogspot.com/2007/02/list-comprehensions-across-languages_18.html List Comprehensions across languages]<br />
<br />
[[Category:Programming constructs]]<br />
[[Category:Articles with example code]]<br />
[[Category:Articles with example Haskell code]]<br />
[[Category:Articles with example Python code]]<br />
[[Category:Articles with example Racket code]]</div>147.251.229.23https://en.wikipedia.org/w/index.php?title=List_comprehension&diff=805421984List comprehension2017-10-15T08:21:07Z<p>147.251.229.23: /* C++ */ add missing include (std::iota is declared in <numeric>)</p>
<hr />
<div>A '''list comprehension''' is a [[Syntax of programming languages|syntactic]] construct available in some [[programming language]]s for creating a list based on existing [[list (computing)|lists]]. It follows the form of the mathematical ''[[set-builder notation]]'' (''set comprehension'') as distinct from the use of [[Map (higher-order function)|map]] and [[Filter (higher-order function)|filter]] functions.<br />
<br />
==Overview==<br />
Consider the following example in [[set-builder notation]].<br />
<br />
:<math>S=\{\,2\cdot x\mid x \in \mathbb{N},\ x^2>3\,\}</math><br />
<br />
This can be read, "<math>S</math> is the set of all numbers "2 times <math>x</math>" where <math>x</math> is an item in the set of [[natural number]]s (<math>\mathbb{N}</math>), for which <math>x</math> squared is greater than <math>3</math>."<br />
<br />
The smallest natural number, x = 1, fails to satisfy the condition x<sup>2</sup>>3 (the condition 1<sup>2</sup>>3 is false) so 2 ·1 is not included in S. The next natural number, 2, does satisfy the condition (2<sup>2</sup>>3) as does every other natural number. Thus S consists of 2 ·2, 2 ·3, 2 ·4... so S = 4, 6, 8, 10,... i.e., all even numbers greater than 2.<br />
<br />
In this annotated version of the example:<br />
:<math>S=\{\,\underbrace{2\cdot x}_{\color{Violet}{\text{output expression}}}\mid \underbrace{x}_{\color{Violet}{\text{variable}}} \in \underbrace{\mathbb{N}}_{\color{Violet}{\text{input set}}},\ \underbrace{x^2>3}_{\color{Violet}{\text{predicate}}}\,\}</math><br />
* <math>x</math> is the variable representing members of an input set.<br />
* <math>\mathbb{N}</math> represents the input set, which in this example is the set of natural numbers<br />
* <math>x^2>3</math> is a [[Predicate (logic)|predicate]] expression acting as a filter on members of the input set.<br />
* <math>2\cdot x</math> is an output expression producing members of the new set from members of the input set that satisfy the predicate expression.<br />
* <math>\{\}</math> braces indicate that the result is a set<br />
* <math>\mid</math> <math>,</math> the vertical bar and the comma are separators.<br />
<br />
A list comprehension has the same syntactic components to represent generation of a list in order from an input [[List (computing)|list]] or [[iterator]]:<br />
* A variable representing members of an input list.<br />
* An input list (or iterator).<br />
* An optional predicate expression.<br />
* And an output expression producing members of the output list from members of the input iterable that satisfy the predicate.<br />
The order of generation of members of the output list is based on the order of items in the input.<br />
<br />
In [[Haskell (programming language)|Haskell's]] list comprehension syntax, this set-builder construct would be written similarly, as:<br />
<source lang="haskell"><br />
s = [ 2*x | x <- [0..], x^2 > 3 ]<br />
</source><br />
<br />
Here, the list <code>[0..]</code> represents <math>\mathbb{N}</math>, <code>x^2>3</code> represents the predicate, and <code>2*x</code> represents the output expression.<br />
<br />
List comprehensions give results in a defined order (unlike the members of sets); and list comprehensions may [[Generator (computer science)|generate]] the members of a list in order, rather than produce the entirety of the list thus allowing, for example, the previous Haskell definition of the members of an infinite list.<br />
<br />
==History==<br />
<br />
The [[SETL]] programming language (1969) has a set formation construct which is similar to list comprehensions. This code prints all prime numbers from 2 to N:<br />
print([n in [2..N] | forall m in {2..n - 1} | n mod m > 0]);<br />
The [[computer algebra system]] [[Axiom (computer algebra system)|AXIOM]] (1973) has a similar construct that processes [[stream (computing)|stream]]s, but the first use of the term "comprehension" for such constructs was in Rod Burstall and John Darlington's description of their functional programming language [[NPL programming language|NPL]] from 1977.<br />
<br />
[[Smalltalk]] block context messages which constitute list comprehensions have been in that language since at least Smalltalk-80.<br />
<br />
Burstall and Darlington's work with NPL influenced many functional programming languages during the 1980s, but not all included list comprehensions. An exception was the influential pure lazy functional programming language [[Miranda programming language|Miranda]], which was released in 1985. The subsequently developed standard pure lazy functional language [[Haskell programming language|Haskell]] includes many of Miranda's features, including list comprehensions.<br />
<br />
Comprehensions were proposed as a query notation for databases<ref>[http://portal.acm.org/citation.cfm?coll=GUIDE&dl=GUIDE&id=135271 Comprehensions, a query notation for DBPLs<!-- Bot generated title -->]</ref> and were implemented in the ''Kleisli'' database query language.<ref>[http://portal.acm.org/citation.cfm?id=351241&dl=ACM&coll=portal The functional guts of the Kleisli query system<!-- Bot generated title -->]</ref><br />
<br />
== Examples in different programming languages ==<br />
<br />
{{main article|Comparison of programming languages (list comprehension)}}<br />
<br />
==Similar constructs==<br />
<br />
===Monad comprehension===<br />
In Haskell, a [[monads in functional programming#do-notation|monad comprehension]] is a generalization of the list comprehension to other [[monads in functional programming]].<br />
<br />
===Set comprehension===<br />
Version 3.x and 2.7 of the Python language introduces syntax for [[set (computer science)|set]] comprehensions. Similar in form to list comprehensions, set comprehensions generate Python sets instead of lists.<br />
<source lang="python"><br />
>>> s = {v for v in 'ABCDABCD' if v not in 'CB'}<br />
>>> print(s)<br />
{'A', 'D'}<br />
>>> type(s)<br />
<class 'set'><br />
>>> <br />
</source><br />
<br />
[[Racket (programming language)|Racket]] set comprehensions generate Racket sets instead of lists.<br />
<source lang="scheme"><br />
(for/set ([v "ABCDABCD"] #:unless (member v (string->list "CB")))<br />
v))<br />
</source><br />
<br />
===Dictionary comprehension===<br />
Version 3.x and 2.7 of the Python language introduced a new syntax for [[associative array|dictionary]] comprehensions, similar in form to list comprehensions but which generate Python [https://docs.python.org/library/stdtypes.html#dict dicts] instead of lists.<br />
<source lang="python"><br />
>>> s = {key: val for key, val in enumerate('ABCD') if val not in 'CB'}<br />
>>> s<br />
{0: 'A', 3: 'D'}<br />
>>> <br />
</source><br />
<br />
Racket hash table comprehensions generate Racket hash tables (one implementation of the Racket dictionary type).<br />
<source lang="scheme"><br />
(for/hash ([(val key) (in-indexed "ABCD")]<br />
#:unless (member val (string->list "CB")))<br />
(values key val))<br />
</source><br />
<br />
===Parallel list comprehension===<br />
The [[Glasgow Haskell Compiler]] has an extension called '''parallel list comprehension''' (also known as '''zip-comprehension''') that permits multiple independent branches of qualifiers within the list comprehension syntax.<br />
Whereas qualifiers separated by commas are dependent ("nested"), qualifier branches separated by pipes are evaluated in parallel (this does not refer to any form of multithreadedness: it merely means that the branches are [[Map (higher-order function)|zipped]]).<br />
<source lang="haskell"><br />
-- regular list comprehension<br />
a = [(x,y) | x <- [1..5], y <- [3..5]]<br />
-- [(1,3),(1,4),(1,5),(2,3),(2,4) ...<br />
<br />
-- zipped list comprehension<br />
b = [(x,y) | (x,y) <- zip [1..5] [3..5]]<br />
-- [(1,3),(2,4),(3,5)]<br />
<br />
-- parallel list comprehension<br />
c = [(x,y) | x <- [1..5] | y <- [3..5]]<br />
-- [(1,3),(2,4),(3,5)]<br />
</source><br />
<br />
Racket's comprehensions standard library contains parallel and nested versions of its comprehensions, distinguished by "for" vs "for*" in the name. For example, the vector comprehensions "for/vector" and "for*/vector" create vectors by parallel versus nested iteration over sequences. The following is Racket code for the Haskell list comprehension examples.<br />
<source lang="scheme"><br />
> (for*/list ([x (in-range 1 6)] [y (in-range 3 6)]) (list x y))<br />
'((1 3) (1 4) (1 5) (2 3) (2 4) (2 5) (3 3) (3 4) (3 5) (4 3) (4 4) (4 5) (5 3) (5 4) (5 5))<br />
> (for/list ([x (in-range 1 6)] [y (in-range 3 6)]) (list x y))<br />
'((1 3) (2 4) (3 5))<br />
</source><br />
<br />
In Python we could do as follows:<br />
<source lang="python"><br />
# regular list comprehension<br />
>>> a = [(x, y) for x in range(1, 6) for y in range(3, 6)]<br />
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), ...<br />
<br />
# parallel/zipped list comprehension<br />
>>> b = [x for x in zip(range(1, 6), range(3, 6))]<br />
[(1, 3), (2, 4), (3, 5)]<br />
</source><br />
<br />
=== XQuery and XPath ===<br />
Like the original NPL use, these are fundamentally database access languages.<br />
<br />
This makes the comprehension concept more important, because it is computationally infeasible to retrieve the entire list and operate on it (the initial 'entire list' may be an entire XML database).<br />
<br />
In XPath, the expression:<br />
<source lang="xquery"><br />
/library/book//paragraph[@style='first-in-chapter']<br />
</source><br />
is conceptually evaluated as a series of "steps" where each step produces a list and the next step applies a filter function to each element in the previous step's output.<ref>{{cite web | url = http://www.w3.org/TR/xpath#section-Location-Steps | title = 2.1 Location Steps | work = XML Path Language (XPath) | date = 16 November 1999 | publisher = [[W3C]]}}</ref><br />
<br />
In XQuery, full XPath is available, but [[FLWOR]] statements are also used, which is a more powerful comprehension construct.<ref>{{cite web | url = http://www.w3schools.com/XQuery/xquery_flwor.asp | title = XQuery FLWOR Expressions | work = [[W3Schools]]}}</ref><br />
<source lang="xquery"><br />
for $b in //book<br />
where $b[@pages < 400]<br />
order by $b//title<br />
return<br />
<shortBook><br />
<title>{$b//title}</title><br />
<firstPara>{($book//paragraph)[1]}</firstPara><br />
</shortBook><br />
</source><br />
Here the XPath //book is evaluated to create a sequence (aka list); the where clause is a functional "filter", the order by sorts the result, and the {{tag|shortBook}} XML snippet is actually an anonymous function that builds/transforms XML for each element in the sequence using the 'map' approach found in other functional languages.<br />
<br />
So, in another functional language the above FLWOR statement may be implemented like this:<br />
<source lang="xquery"><br />
map(<br />
newXML(shortBook, newXML(title, $1.title), newXML(firstPara, $1...))<br />
filter(<br />
lt($1.pages, 400),<br />
xpath(//book)<br />
)<br />
)<br />
</source><br />
<br />
=== LINQ in C# ===<br />
<br />
[[C Sharp (programming language)|C#]] 3.0 has a group of related features called [[LINQ]], which defines a set of query operators for manipulating object enumerations.<br />
<br />
<source lang="csharp"><br />
var s = Enumerable.Range(0, 100).Where(x => x*x > 3).Select(x => x*2);<br />
</source><br />
<br />
It also offers an alternative comprehension syntax, reminiscent of SQL:<br />
<br />
<source lang="csharp"><br />
var s = from x in Enumerable.Range(0, 100) where x*x > 3 select x*2;<br />
</source><br />
<br />
LINQ provides a capability over typical List Comprehension implementations. When the root object of the comprehension implements the IQueryable interface, rather than just executing the chained methods of the comprehension, the entire sequence of commands are converted into an Abstract Syntax Tree (AST) object, which is passed to the IQueryable object to interpret and execute.<br />
<br />
This allows, amongst other things, for the IQueryable to <br />
* rewrite an incompatible or inefficient comprehension<br />
* translate the AST into another query language (e.g. SQL) for execution<br />
<br />
=== C++ ===<br />
C++ does not have any language features directly supporting list comprehensions but [[operator overloading]] (e.g., overloading |, >>, >>=) has been used successfully to provide expressive syntax for "embedded" query [[Domain-specific language|DSL]]s. Alternatively, list comprehensions can be constructed using the [[erase-remove idiom]] to select elements in a container and the STL algorithm for_each to transform them.<br />
<source lang="cpp"><br />
#include <algorithm><br />
#include <list><br />
#include <numeric><br />
<br />
using namespace std;<br />
<br />
template<class C, class P, class T><br />
C&& comprehend(C&& source, const P& predicate, const T& transformation)<br />
{<br />
// initialize destination<br />
C d = forward<C>(source);<br />
<br />
// filter elements<br />
d.erase(remove_if(begin(d), end(d), predicate), end(d));<br />
<br />
// apply transformation<br />
for_each(begin(d), end(d), transformation);<br />
<br />
return d;<br />
}<br />
<br />
int main()<br />
{<br />
list<int> range(10); <br />
// range is a list of 10 elements, all zero<br />
iota(begin(range), end(range), 1);<br />
// range now contains 1,2,...,10<br />
<br />
list<int> result = comprehend(<br />
range,<br />
[](int x){return x*x <= 3;},<br />
[](int &x){x *= 2;});<br />
// result now contains 4,6,...,20<br />
}<br />
</source><br />
There is some effort in providing C++ with list-comprehension constructs/syntax similar to the set builder notation.<br />
* In [[Boost C++ Libraries|Boost]].Range [http://www.boost.org/libs/range] library there is a notion of adaptors [http://www.boost.org/libs/range/doc/html/range/reference/adaptors.html] that can be applied to any range and do filtering, transformation etc. With this library, the original Haskell example would look like (using Boost.Lambda [http://www.boost.org/libs/lambda] for anonymous filtering and transforming functions) ([http://codepad.org/y4bpgLJu Full example]):<source lang="cpp"><br />
counting_range(1,10) | filtered( _1*_1 > 3 ) | transformed(ret<int>( _1*2 ))<br />
</source><br />
* This<ref>{{cite web | url = http://mfoliveira.org/blog/2011/01/04/simple-list-comprehension-in-cp-using-preprocessor-macros/ | title = Single-variable List Comprehension in C++ using Preprocessor Macros}}</ref> implementation uses a macro and overloads the << operator. It evaluates any expression valid inside an 'if', and any variable name may be chosen. It's not [[thread safety|threadsafe]], however. Usage example:<source lang="cpp"><br />
list<int> N;<br />
list<double> S;<br />
<br />
for (int i = 0; i < 10; i++)<br />
N.push_back(i);<br />
<br />
S << list_comprehension(3.1415 * x, x, N, x*x > 3)<br />
</source><br />
* This<ref>{{cite web | url = http://www.tedunangst.com/listcc.html | title = C++ list comprehensions}}</ref> implementation provides head/tail slicing using classes and operator overloading, and the | operator for filtering lists (using functions). Usage example:<source lang="cpp"><br />
bool even(int x) { return x % 2 == 0; }<br />
bool x2(int &x) { x *= 2; return true; }<br />
<br />
list<int> l, t;<br />
int x, y;<br />
<br />
for (int i = 0; i < 10; i++)<br />
l.push_back(i);<br />
<br />
(x, t) = l | x2;<br />
(t, y) = t;<br />
<br />
t = l < 9;<br />
t = t < 7 | even | x2;<br />
</source><br />
* Language for Embedded Query and Traversal (LEESA<ref>{{cite web | url = http://www.dre.vanderbilt.edu/LEESA/ | title = Language for Embedded Query and Traversal (LEESA)}}</ref>) is an embedded DSL in C++ that implements X-Path-like queries using operator overloading. The queries are executed on richly typed xml trees obtained using xml-to-c++ binding from an XSD. There is absolutely no string encoding. Even the names of the xml tags are classes and therefore, there is no way for typos. If a LEESA expression forms an incorrect path that does not exist in the data model, the C++ compiler will reject the code.<br>Consider a catalog xml.<source lang="xml"><br />
<catalog><br />
<book><br />
<title>Hamlet</title><br />
<price>9.99</price><br />
<author><br />
<name>William Shakespeare</name><br />
<country>England</country><br />
</author><br />
</book><br />
<book>...</book><br />
...<br />
</catalog><br />
</source><br />
LEESA provides >> for X-Path's / separator. Interestingly, X-Path's // separator that "skips" intermediate nodes in the tree is implemented in LEESA using what's known as Strategic Programming. In the example below, catalog_, book_, author_, and name_ are instances of catalog, book, author, and name classes, respectively.<br />
<source lang="cpp"><br />
// Equivalent X-Path: "catalog/book/author/name"<br />
std::vector<name> author_names = <br />
evaluate(root, catalog_ >> book_ >> author_ >> name_);<br />
<br />
// Equivalent X-Path: "catalog//name"<br />
std::vector<name> author_names = <br />
evaluate(root, catalog_ >> DescendantsOf(catalog_, name_));<br />
<br />
// Equivalent X-Path: "catalog//author[country=="England"]"<br />
std::vector<name> author_names = <br />
evaluate(root, catalog_ >> DescendantsOf(catalog_, author_)<br />
>> Select(author_, [](const author & a) { return a.country()=="England"; })<br />
>> name_);<br />
</source><br />
<br />
==See also==<br />
*The [[Select (SQL)|SELECT]] statement together with its FROM and WHERE clauses in [[SQL#Queries|SQL]]<br />
<br />
==Notes and references==<br />
{{reflist}}<br />
*[http://ftp.sunet.se/foldoc/foldoc.cgi?list+comprehension List Comprehension] in The Free On-line Dictionary of Computing, Editor Denis Howe.<br />
*{{cite conference | first = Phil | last = Trinder | url = http://portal.acm.org/citation.cfm?coll=GUIDE&dl=GUIDE&id=135271 | title = Comprehensions, a query notation for DBPLs | booktitle = Proceedings of the third international workshop on Database programming languages: bulk types & persistent data, Nafplion, Greece | pages = 55–68 | year = 1992}}<br />
*{{cite conference | first = Philip | last = Wadler |url = http://citeseer.ist.psu.edu/wadler92comprehending.html | title = Comprehending Monads | booktitle = Proceedings of the 1990 ACM Conference on LISP and Functional Programming, Nice | year = 1990}}<br />
*{{cite conference | first = Limsoon | last = Wong | url = http://portal.acm.org/citation.cfm?id=351241&dl=ACM&coll=portal | title = The Functional Guts of the Kleisli Query System | conference = International Conference on Functional Programming | booktitle = Proceedings of the fifth ACM SIGPLAN international conference on Functional programming | pages = 1–10 | year = 2000}}<br />
<br />
===Haskell===<br />
*The Haskell 98 Report, chapter [http://haskell.org/onlinereport/exps.html#list-comprehensions 3.11 List Comprehensions].<br />
*The Glorious Glasgow Haskell Compilation System User's Guide, chapter [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#parallel-list-comprehensions 7.3.4 Parallel List Comprehensions].<br />
*The Hugs 98 User's Guide, chapter [http://cvs.haskell.org/Hugs/pages/users_guide/hugs-ghc.html#ZIP-COMPREHENSION 5.1.2 Parallel list comprehensions (a.k.a. zip-comprehensions)].<br />
<br />
===OCaml===<br />
* [http://batteries.forge.ocamlcore.org/ OCaml Batteries Included]<br />
* [http://batteries.forge.ocamlcore.org/doc.preview:batteries-alpha3/html/extensions.html Language extensions introduced in OCaml Batteries Included]<br />
<br />
===Python===<br />
* The Python Tutorial, [https://docs.python.org/tutorial/datastructures.html#list-comprehensions List Comprehensions].<br />
* Python Language Reference, [https://docs.python.org/reference/expressions.html#list-displays List displays].<br />
* Python Enhancement Proposal [https://www.python.org/peps/pep-0202.html PEP 202: List Comprehensions].<br />
* Python Language Reference, [https://docs.python.org/reference/expressions.html#generator-expressions Generator expressions].<br />
* Python Enhancement Proposal [https://python.org/peps/pep-0289.html PEP 289: Generator Expressions].<br />
<br />
===Common Lisp===<br />
* [http://rali.iro.umontreal.ca/Publications/urls/LapalmeLispComp.pdf Implementation of a Lisp comprehension macro] by Guy Lapalme<br />
<br />
===Clojure===<br />
* [https://clojuredocs.org/clojure.core/for Clojure API documentation - ''for'' macro]<br />
<br />
===Axiom===<br />
* [http://page.axiom-developer.org/zope/mathaction/Streams Axiom stream examples]<br />
<br />
==External links==<br />
* SQL-like set operations with list comprehension one-liners in the [http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159974 Python Cookbook]<br />
* [http://lambda-the-ultimate.org/classic/message11326.html Discussion on list comprehensions in Scheme and related constructs]<br />
* [http://langexplr.blogspot.com/2007/02/list-comprehensions-across-languages_18.html List Comprehensions across languages]<br />
<br />
[[Category:Programming constructs]]<br />
[[Category:Articles with example code]]<br />
[[Category:Articles with example Haskell code]]<br />
[[Category:Articles with example Python code]]<br />
[[Category:Articles with example Racket code]]</div>147.251.229.23