Summary
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. Consider the following example in set-builder notation. or often This can be read, " is the set of all numbers "2 times " SUCH THAT is an ELEMENT or MEMBER of the set of natural numbers (), AND squared is greater than ." 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 = {4, 6, 8, 10,...}. S is, in other words, the set of all even numbers greater than 2. In this annotated version of the example: is the variable representing members of an input set. represents the input set, which in this example is the set of natural numbers is a predicate expression acting as a filter on members of the input set. 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 the vertical bar is read as "SUCH THAT". The bar and the colon ":" are used interchangeably. commas separate the predicates and can be read as "AND". A list comprehension has the same syntactic components to represent generation of a list in order from an input list or iterator: A variable representing members of an input list. An input list (or iterator). An optional predicate expression. And an output expression producing members of the output list from members of the input iterable that satisfy the predicate. 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
About this result
This page is automatically generated and may contain information that is not correct, complete, up-to-date, or relevant to your search query. The same applies to every other page on this website. Please make sure to verify the information with EPFL's official sources.