List comprehension explained

A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions.

Overview

Consider the following example in mathematical set-builder notation.

S=\{2 ⋅ x\midx\inN,x2>3\}

or often

S=\{2 ⋅ x:x\inN,x2>3\}

This can be read, "

S

is the set of all numbers "2 times

x

" SUCH THAT

x

is an ELEMENT or MEMBER of the set of natural numbers (

N

), AND

x

squared is greater than

3

."

The smallest natural number, x = 1, fails to satisfy the condition x2>3 (the condition 12>3 is false) so 2 ·1 is not included in S. The next natural number, 2, does satisfy the condition (22>3) as does every other natural number. Thus x consists of 2, 3, 4, 5... Since the set consists of all numbers "2 times x" it is given by S = . S is, in other words, the set of all even numbers greater than 2.

In this annotated version of the example:

S=\{\underbrace{2 ⋅ x}\color{Violet{outputexpression

}}\mid \underbrace_ \in \underbrace_,\ \underbrace_\}

x

is the variable representing members of an input set.

N

represents the input set, which in this example is the set of natural numbers

x2>3

is a predicate expression acting as a filter on members of the input set.

2 ⋅ x

is an output expression producing members of the new set from members of the input set that satisfy the predicate expression.

\{\}

braces indicate that the result is a set

\mid

,

the vertical bar is read as "SUCH THAT". The bar and the colon ":" are used interchangeably.

A list comprehension has the same syntactic components to represent generation of a list in order from an input list or iterator:

The order of generation of members of the output list is based on the order of items in the input.

In Haskell's list comprehension syntax, this set-builder construct would be written similarly, as:s = [2*x | x <- [0..], x^2 > 3 ]

Here, the list [0..] represents

N

, x^2>3 represents the predicate, and 2*x represents the output expression.

List comprehensions give results in a defined order (unlike the members of sets); and list comprehensions may 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.

History

The existence of related constructs predates the use of the term "List Comprehension". The SETL programming language (1969) has a set formation construct which is similar to list comprehensions. E.g., this code prints all prime numbers from 2 to : print([n in [2..N] | forall m in | n mod m > 0]);The computer algebra system AXIOM (1973) has a similar construct that processes streams.

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 from 1977. In his retrospective "Some History of Functional Programming Languages",[1] David Turner recalls:

}}

In a footnote attached to the term "list comprehension", Turner also notes

Burstall and Darlington's work with NPL influenced many functional programming languages during the 1980s, but not all included list comprehensions. An exception was Turner's influential, pure, lazy, functional programming language Miranda, released in 1985. The subsequently developed standard pure lazy functional language Haskell includes many of Miranda's features, including list comprehensions.

Comprehensions were proposed as a query notation for databases[2] and were implemented in the Kleisli database query language.[3]

Examples in different programming languages

See main article: Comparison of programming languages (list comprehension).

Similar constructs

Monad comprehension

In Haskell, a monad comprehension is a generalization of the list comprehension to other monads in functional programming.

Set comprehension

The Python language introduces syntax for set comprehensions starting in version 2.7. Similar in form to list comprehensions, set comprehensions generate Python sets instead of lists.>>> s = >>> print(s)>>> type(s)>>>

Racket set comprehensions generate Racket sets instead of lists.(for/set ([v "ABCDABCD"] #:unless (member v (string->list "CB"))) v))

Dictionary comprehension

The Python language introduced a new syntax for dictionary comprehensions in version 2.7, similar in form to list comprehensions but which generate Python dicts instead of lists.>>> s = >>> s>>>

Racket hash table comprehensions generate Racket hash tables (one implementation of the Racket dictionary type).(for/hash ([(val key) (in-indexed "ABCD")] #:unless (member val (string->list "CB"))) (values key val))

Parallel list comprehension

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.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 zipped).-- regular list comprehensiona = [(x,y) | x <- [1..5], y <- [3..5]]-- [(1,3),(1,4),(1,5),(2,3),(2,4) ... -- zipped list comprehension b = [(x,y) | (x,y) <- zip [1..5] [3..5]]-- [(1,3),(2,4),(3,5)]

-- parallel list comprehensionc = [(x,y) | x <- [1..5] | y <- [3..5]]-- [(1,3),(2,4),(3,5)]

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.> (for*/list ([x (in-range 1 6)] [y (in-range 3 6)]) (list x y))'((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))> (for/list ([x (in-range 1 6)] [y (in-range 3 6)]) (list x y))'((1 3) (2 4) (3 5))

In Python, we could do as follows:>>> # regular list comprehension>>> a = [(x, y) for x in range(1, 6) for y in range(3, 6)][(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), ... >>> >>> # parallel/zipped list comprehension >>> b = [x for x in zip(range(1, 6), range(3, 6))][(1, 3), (2, 4), (3, 5)]

In Julia, practically the same results can be achieved as follows:

  1. regular array comprehension

>>> a = [(x, y) for x in 1:5 for y in 3:5]

  1. parallel/zipped array comprehension

>>> b = [x for x in zip(1:3, 3:5)]with the only difference that instead of lists, in Julia, we have arrays.

XQuery and XPath

Like the original NPL use, these are fundamentally database access languages.

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).

In XPath, the expression:/library/book//paragraph[@style='first-in-chapter']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.[4]

In XQuery, full XPath is available, but FLWOR statements are also used, which is a more powerful comprehension construct.[5] for $b in //bookwhere $b[@pages < 400]order by $b//titlereturn 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 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.

So, in another functional language the above FLWOR statement may be implemented like this:map(newXML(shortBook, newXML(title, $1.title), newXML(firstPara, $1...)) filter(lt($1.pages, 400), xpath(//book)))

LINQ in C#

C# 3.0 has a group of related features called LINQ, which defines a set of query operators for manipulating object enumerations.

var s = Enumerable.Range(0, 100).Where(x => x * x > 3).Select(x => x * 2);

It also offers an alternative comprehension syntax, reminiscent of SQL:

var s = from x in Enumerable.Range(0, 100) where x * x > 3 select x * 2;

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.

This allows, amongst other things, for the IQueryable to

C++

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 languages (DSL). 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.

  1. include
  2. include
  3. include

using namespace std;

templateC comprehend(C&& source, const P& predicate, const T& transformation)

int mainThere is some effort in providing C++ with list-comprehension constructs/syntax similar to the set builder notation.

counting_range(1,10) | filtered(_1*_1 > 3) | transformed(ret(_1*2))

list N;list S;

for (int i = 0; i < 10; i++) N.push_back(i);

S << list_comprehension(3.1415 * x, x, N, x * x > 3)

bool even(int x) bool x2(int &x)

list l, t;int x, y;

for (int i = 0; i < 10; i++) l.push_back(i);

(x, t) = l | x2;(t, y) = t;

t = l < 9;t = t < 7 | even | x2;

Hamlet 9.99 William Shakespeare England ......LEESA provides >> for XPath's / separator. XPath'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.// Equivalent X-Path: "catalog/book/author/name"std::vector author_names = evaluate(root, catalog_ >> book_ >> author_ >> name_);

// Equivalent X-Path: "catalog//name"std::vector author_names = evaluate(root, catalog_ >> DescendantsOf(catalog_, name_));

// Equivalent X-Path: "catalog//author[country=="England"]"std::vector author_names = evaluate(root, catalog_ >> DescendantsOf(catalog_, author_) >> Select(author_, [](const author & a)) >> name_);

See also

Notes and references

External links

Axiom

Clojure

Common Lisp

Haskell

OCaml

Python

Notes and References

  1. David . Turner . Some history of functional programming languages . International Symposium on Trends in Functional Programming, Springer, Berlin, Heidelberg . 1–20 . 2012.
  2. http://portal.acm.org/citation.cfm?coll=GUIDE&dl=GUIDE&id=135271 Comprehensions, a query notation for DBPLs
  3. http://portal.acm.org/citation.cfm?id=351241&dl=ACM&coll=portal The functional guts of the Kleisli query system
  4. Web site: 2.1 Location Steps . XML Path Language (XPath) . 16 November 1999 . . 24 December 2008 . https://web.archive.org/web/20121209085946/http://www.w3.org/TR/xpath/#section-Location-Steps . 9 December 2012 . dead .
  5. Web site: XQuery FLWOR Expressions . . dead . https://web.archive.org/web/20111008001258/http://w3schools.com/xquery/xquery_flwor.asp . 2011-10-08 .
  6. Web site: Single-variable List Comprehension in C++ using Preprocessor Macros . 2011-01-09 . https://web.archive.org/web/20110821211656/http://mfoliveira.org/blog/2011/01/04/simple-list-comprehension-in-cp-using-preprocessor-macros/ . 2011-08-21 . dead .
  7. Web site: C++ list comprehensions . 2011-01-09 . https://web.archive.org/web/20170707125836/http://www.tedunangst.com/listcc.html . 2017-07-07 . dead .
  8. Web site: Language for Embedded Query and Traversal (LEESA).