List comprehensions can be expressed with the loop macro's collect keyword. Conditionals are expressed with if, as follows: )
Cobra
List the names of customers: names = for cust in customers get cust.name
List the customers with balances: names = for cust in customers where cust.balance > 0
List the names of customers with balances: names = for cust in customers where cust.balance > 0 get cust.name
The general forms: for VAR in ENUMERABLE get EXPR for VAR in ENUMERABLE where CONDITION
Note that by putting the condition and expression after the variable name and enumerable object, editors and IDEs can provide autocompletion on the members of the variable.
List comprehensions are the part of a greater family of language constructs called computation expressions.
Groovy
.findAll.collect
Haskell
, x * x > 3]
An example of a list comprehension using multiple generators: pyth = , y <- , z <- , x^2 + y^2 z^2]
Io
By using Range object, Io language can create list as easy as in other languages: Range 0 to asList select map
ISLISP
List comprehensions can be expressed with the for special form. Conditionals are expressed with if, as follows: )) ) ))
Java
Java with the Streams API, which includes the IntStream interface which allows operations like the following: List ns = IntStream.range .filter .map .boxed.collect);
JavaScript
.filter.map function* range
Julia
Julia supports comprehensions using the syntax: y =
and multidimensional comprehensions like: z =
It is also possible to add a condition: v =
And just changing square brackets to the round one, we get a generator: g =
uses the following syntax to express list comprehensions over finite lists: S =
A generator expression may be used in Python versions >= 2.4 which gives lazy evaluation over its input, and can be used with generators to iterate over 'infinite' input such as the count generator function which returns successive integers: from itertools import count S =
.
R
x <- 0:100 S <- 2 * x
Racket
)
An example with multiple generators: ] #:when ) )) )
Raku
my @s = ;
Ruby
.select.map
Rust
let ns: Vec<_> =.filter.map.collect;
Scala
Using the for-comprehension: val s = for yield 2*x
Scheme
List comprehensions are supported in Scheme through the use of the SRFI-42 library. )
An example of a list comprehension using multiple generators: ) )) )
SETL
s := ;
Smalltalk
collect:
Swift
// 0 2 4 6... 18 let timesTwo =.map
// Suppose isPrime: -> Bool a function that checks if its argument is a prime number let primeBelow100 =.filter
Visual Prolog
S =
Windows PowerShell
$s = which is short-hand notation of: $s = 0..100 | where-object | foreach-object