1 title:: List Comprehensions
2 categories:: Language, Collections
3 summary:: list comprehensions and generator expressions
7 List comprehensions are a syntactic feature of functional programming languages like Miranda, Haskell, and Erlang which were later copied into Python.
8 You can search the web for "list comprehensions" or "generator expressions" to learn more.
9 Basically list comprehensions are for getting a series of solutions to a problem.
11 in SC these are just a syntax macro for a longer expression. read this as emphasis:: "all [x,y] for x in 1..5, y in 1..x, such that x+y is prime" :::
13 all {:[x,y], x <- (1..5), y <- (1..x), (x+y).isPrime }
17 [ [ 1, 1 ], [ 2, 1 ], [ 3, 2 ], [ 4, 1 ], [ 4, 3 ], [ 5, 2 ] ]
20 the list comprehension above is equivalent to the following code:
22 all(Routine.new({ (1..5).do {|x| (1..x).do {|y| if ((x+y).isPrime) {[x,y].yield} }}}));
24 ..but much more concise and much easier to keep in your head than writing it out.
26 In the list comprehension compiler, simple series like code::(1..5):: and code::(1..x):: are treated as special cases and implemented as loops rather than making a collection.
28 A list comprehension in SC is really a link::Classes/Routine::. You can use the code::all:: message to collect all of the Routine's results into a list.
30 section:: A few examples
32 all {: x/(x+1), x <- (1..5) }
34 [ 0.5, 0.66666666666667, 0.75, 0.8, 0.83333333333333 ]
37 all {:[x,y], x <- (1..3), y <- [\a,\b,\c] }
39 [ [ 1, a ], [ 1, b ], [ 1, c ], [ 2, a ], [ 2, b ], [ 2, c ], [ 3, a ], [ 3, b ], [ 3, c ] ]
42 all {:[x,y], x <- (0..3), y <- (x..0) }
44 [ [ 0, 0 ], [ 1, 1 ], [ 1, 0 ], [ 2, 2 ], [ 2, 1 ], [ 2, 0 ], [ 3, 3 ], [ 3, 2 ], [ 3, 1 ], [ 3, 0 ] ]
47 all {:y, x <- (1..4), y <- (x..1) }
49 [ 1, 2, 1, 3, 2, 1, 4, 3, 2, 1 ]
55 // a function to generate intervals between all pairs of notes in a chord voicing
57 all {: chord[i+gap] - chord[i],
58 gap <- (1 .. chord.lastIndex),
59 i <- (0 .. chord.lastIndex - gap)
63 intervals.([0,4,7,10]).postln;
64 intervals.([0,1,3,7]).postln;
72 all {:[y, z], x<-(0..30), var y = x.nthPrime, var z = 2 ** y - 1, z.asInteger.isPrime.not }
73 [ [ 11, 2047 ], [ 23, 8388607 ], [ 29, 536870911 ] ] // mersenne numbers which are no primes
76 section:: Qualifier Clauses
78 A list comprehension begins with code:: {: :: and contains a body followed by several qualifier clauses separated by commas.
80 {: body , qualifiers }
82 There are several types of qualifier clauses that can appear after the body.
84 subsection:: generator clause
86 The basic clause is the generator clause. Its syntax is
90 The expression should be something that can respond meaningfully to 'do' such as a collection or a stream.
91 The name takes on each value of the expression.
92 The name is a local variable whose scope extends to all clauses to the right. The name is also in scope in the body.
94 all {: x, x <- (1..3) }
99 all {: x, x <- [\a, \b, \c] }
104 all {: x, x <- (1!3)++(2!2)++3 }
108 multiple generators act like nested loops.
110 all {: [x,y], x <- (1..2), y <- (10,20..30) }
112 [ [ 1, 10 ], [ 1, 20 ], [ 1, 30 ], [ 2, 10 ], [ 2, 20 ], [ 2, 30 ] ]
114 generators can depend on previous values.
116 all {: x, x <- (1..3), y <- (1..x) }
121 all {: x, x <- (1..3), y <- (1..4-x) }
126 subsection:: guard clause
128 A guard clause is simply an expression. It should return a boolean value.
132 The guard acts as a filter on the results and constrains the search.
134 all {: x, x <- (0..10), x.odd }
138 code::x.odd:: is the guard and causes all even numbers to be skipped.
140 all {: x, x <- (0..30), (x % 5 == 0) || x.isPowerOfTwo }
142 [ 0, 1, 2, 4, 5, 8, 10, 15, 16, 20, 25, 30 ]
144 you can have multiple guards.
146 all {: [x,y], x <- (0..10), (x % 5 == 0) || x.isPowerOfTwo, y <- (1..2), (x+y).even }
148 [ [ 0, 2 ], [ 1, 1 ], [ 2, 2 ], [ 4, 2 ], [ 5, 1 ], [ 8, 2 ], [ 10, 2 ] ]
151 subsection:: var clause
153 A var clause lets you create a new variable binding that you can use in your expressions.
154 The scope of the name extends to all clauses to the right and in the body.
158 Unlike the generator clause, the name is bound to a single value, it doesn't iterate.
160 all {: z, x <- (1..20), var z = (x*x-x) div: 2, z.odd }
162 [ 1, 3, 15, 21, 45, 55, 91, 105, 153, 171 ]
165 subsection:: side effect clause
167 This clause lets you insert code to do some side effect like printing.
172 all {: z, x <- (1..20), var z = (x*x-x) div: 2, :: [x,z].postln, z.even }
175 subsection:: termination clause
177 The termination clause is for stopping further searching for results. Once the expression becomes false,
185 all {: z, x <- (1..20), var z = (x*x-x) div: 2, :: [x,z].postln, z < 50 }
188 using a termination clause. this one stops searching, so does less work than the above.
190 all {: z, x <- (1..20), var z = (x*x-x) div: 2, :: [x,z].postln, :while z < 50 }
193 section:: Constrained Search
195 list comprehensions can solve constrained combinatorial problems like this one:
197 Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
198 Baker does not live on the top floor. Cooper does not live on the bottom floor.
199 Fletcher does not live on either the top or the bottom floor. Miller lives on a higher floor than does Cooper.
200 Smith does not live on a floor adjacent to Fletcher's. Fletcher does not live on a floor adjacent to Cooper's.
201 Where does everyone live?
204 z = {: [baker, cooper, fletcher, miller, smith] ,
206 baker <- floors, baker != 5, // Baker does not live on the top floor.
207 // remove baker's floor from the list.
208 // var creates a new scope, so the 'floors' on the left is a new binding.
209 var floors = floors.removing(baker),
210 cooper <- floors, cooper != 1, // Cooper does not live on the bottom floor.
211 var floors = floors.removing(cooper), // remove cooper's floor from the list.
212 fletcher <- floors, (fletcher != 5) && (fletcher != 1) // Fletcher does not live on either top or bottom floor.
213 && (absdif(fletcher, cooper) > 1), // Fletcher does not live on a floor adjacent to Cooper's.
214 var floors = floors.removing(fletcher), // remove fletcher's floor
215 miller <- floors, miller > cooper, // Miller lives on a higher floor than does Cooper.
216 var floors = floors.removing(miller), // remove miller's floor
217 smith <- floors, absdif(fletcher, smith) > 1 // Smith does not live on a floor adjacent to Fletcher's.
221 z.next; // [3, 2, 4, 5, 1 ]
222 z.next; // nil. only one solution
225 combinatorial problems can take a lot of time to run.
226 you can reorder the above tests to make it run faster. generally you want to search the most constrained variables first.
227 the most constrained person above is fletcher, so he should be searched first, then cooper, etc.
232 Here is the BNF grammar for list comprehensions in SC.
237 <list_compre> ::= "{:" <body> ',' <qualifiers> "}"
241 <exprseq> ::= <expr> { ";" <expr> }
243 <qualifiers> ::= <qualifier> { ',' <qualifiers> }
245 <qualifier> ::= <generator> | <guard> | <binding> | <side_effect> | <termination>
247 <generator> ::= <name> "<-" <exprseq>
249 <guard> ::= <exprseq>
251 <binding> ::= "var" <name> "=" <exprseq>
253 <side_effect> ::= "::" <exprseq>
255 <termination> ::= ":while" <exprseq>
258 section:: Code Generation
260 For each of the above clauses, here is how the code is generated. The body acts as the innermost qualifier.
261 By understanding these translations, you can better understand how scoping and control flow work in list comprehensions.
264 ## generator || code::
265 expr.do {|name| ..next qualifier.. }
269 if (expr) { ..next qualifier.. }
273 {|name| ..next qualifier.. }.value(expr)
276 ## side effect || code::
277 expr ; ..next qualifier..
280 ## termination || code::
281 if (expr) { ..next qualifier.. }{ nil.alwaysYield }