File: Control-Structures.schelp

package info (click to toggle)
supercollider 1%3A3.13.0%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 80,292 kB
  • sloc: cpp: 476,363; lisp: 84,680; ansic: 77,685; sh: 25,509; python: 7,909; makefile: 3,440; perl: 1,964; javascript: 974; xml: 826; java: 677; yacc: 314; lex: 175; objc: 152; ruby: 136
file content (414 lines) | stat: -rw-r--r-- 11,124 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
title::Control Structures
summary:: flow control
categories:: Language
related:: Classes/Boolean

Control structures in SuperCollider are implemented via message sends. Here are a few of those available.
See link::Reference/Syntax-Shortcuts:: for the various ways expressions can be written.

section:: Basic Control Structures

method:: if

Conditional execution is implemented via the code::if:: message. The code::if:: message is sent to an expression which must return a link::Classes/Boolean:: value.

In addition it takes two arguments: a function to execute if the expression is true and another optional function to execute if the expression is false. The code::if:: message returns the value of the function which is executed. If the falseFunc is not present and the expression is false then the result of the if message is nil.

discussion::
Syntax
code::
if(expr) { true body } { false body };

// alternate
if(expr, trueFunc, falseFunc);

// possible but harder to read, so, not preferred
expr.if (trueFunc, falseFunc);
::

Examples
code::
if([false, true].choose) {
	"expression was true".postln  // true function
} {
	"expression was false".postln  // false function
};
)

(
var a = 1, z;
z = if(a < 5) { 100 } { 200 };
z.postln;
)

(
var x;
if(x.isNil) { x = 99 };
x.postln;
)
::


method:: while

The while message implements conditional execution of a loop. If the testFunc answers true when evaluated, then the loopFunc is evaluated and the process is repeated. Once the testFunc returns false, the loop terminates.

discussion::
Syntax
code::
while { testFunc body } { loopFunc body };

// alternate
while({ testFunc body }, { loopFunc body });

// possible but harder to read, so, not preferred
{ testFunc body }.while({ loopFunc body });
::

Example
code::
(
i = 0;
while { i < 5 } { i = i + 1; "boing".postln };
)
::

while expressions are also optimized by the compiler if they do not contain variable declarations in the testFunc and the loopFunc.


method:: for

The for message implements iteration over an integer series from a starting value to an end value stepping by one each time. A function is evaluated each iteration and is passed the iterated numeric value as an argument.

discussion::
Syntax
code::
for(startValue, endValue) { loop body }

// alternate
for(startValue, endValue, function)

// possible but harder to read, so, not preferred
startValue.for ( endValue, function )
::

Example
code::
for(3, 7) { arg i; i.postln };  // prints values 3 through 7
::

method:: forBy

The forBy selector implements iteration over an integer series with a variable step size. A function is evaluated each iteration and is passed the iterated numeric value as an argument.

discussion::
Syntax
code::
forBy(startValue, endValue, stepValue) { loop body };

forBy(startValue, endValue, stepValue, function);

// possible but harder to read, so, not preferred
startValue.forBy(endValue, stepValue, function);
::

Example
code::
forBy(0, 8, 2) { arg i; i.postln };  // prints values 0 through 8 by 2's
::


method:: do

Do is used to iterate over a link::Classes/Collection::. Positive Integers also respond to code::do:: by iterating from zero up to their value. Collections iterate, calling the function for each object they contain. Other kinds of Objects respond to do by passing themselves to the function one time. The function is called with two arguments, the item, and an iteration counter.

discussion::
Syntax
code::
collection.do { loop body };

// alternate
collection.do(function)

// alternates, rarely seen
do(collection, function)
do(collection) { loop body };
::

Example
code::
[ 1, 2, "abc", (3@4) ].do { arg item, i; [i, item].postln; };

5.do { arg item; item.postln }; // iterates from zero to four

"you".do { arg item; item.postln }; // a String is a collection of characters

'they'.do { arg item; item.postln }; // a Symbol is a singular item

(8..20).do { arg item; item.postln }; // iterates from eight to twenty

(8,10..20).do { arg item; item.postln }; // iterates from eight to twenty, with stepsize two

Routine {
	var i = 10;
	while { i > 0 } {
		i.yield;
		i = i - 5.0.rand
	}
}.do { arg item; item.postln };  // 'do' applies to the Routine
::

Note:: The syntax code::(8..20).do:: uses an optimization to avoid generating an array that is used only for iteration (but which would be discarded thereafter). The return value of code:: (8..20).do { |item| item.postln } :: is 8, the starting value.

However, if code::do:: is written as an infix binary operator, as in code::(8..20) do: { |item| item.postln }::, then it will generate the series as an array first, before calling Array:do. One side effect of this is that it is valid to code::do:: over an infinite series within a routine only if code::do:: is written as a method call. If it is written as a binary operator, you will get a "wrong type" error because the array must be finite.

code::
// OK: 'do' is a method call
r = Routine {
	(8 .. ).do { |i|
		i.yield;
	};
};

r.next;
-> 8
-> 9 etc.

// ERROR: 'do' is an operator
r = Routine {
	(8 .. ) do: { |i|
		i.yield;
	};
};

r.next;

ERROR: Primitive '_SimpleNumberSeries' failed.
Wrong type.
::
::

method:: switch

Object implements a switch method which allows for conditional evaluation with multiple cases. These are implemented as pairs of test objects (tested using if this == test.value) and corresponding functions to be evaluated if true.

The switch statement will be inlined if the test objects are all Floats, Integers, Symbols, Chars, nil, false, true and if the functions have no variable or argument declarations. The inlined switch uses a hash lookup (which is faster than nested if statements), so it should be very fast and scale to any number of clauses.

note::Hash lookup by definition implies testing emphasis::identity:: rather than equality: a code::switch:: construction that is not inlined will test code::==::, while one that is inlined will test code::===::. See the examples. One implication is that strings should be avoided: code::switch(text) { "abc" } { ... }:: may not match, even if code::text == "abc"::. Symbols are preferred.::

note::Floating point numbers may sometimes appear to be equal while differing slightly in their binary representation: code::(2/3) == (1 - (1/3)):: is false. Therefore floats should be avoided in code::switch:: constructions.::

discussion::
Syntax
code::
switch(value)
{ testvalue1 } { truebody1 }
{ testvalue2 } { truebody2 }
{ testvalue3 } { truebody3 }
{ testvalue4 } { truebody4 }
...
{ defaultbody };

switch(value,
        testvalue1, trueFunction1,
        testvalue2, trueFunction2,
        ...
        testvalueN, trueFunctionN,
        defaultFunction
);
::

Examples
code::
(
var x = 0; //also try 1
switch(x, 0, { "hello" }, 1, { "goodbye" })
)

(
var x = 0; //also try 1
switch(x) { 0 } { "hello" } { 1 } { "goodbye" };
)

(
var x, z;
z = [0, 1, 1.1, 1.3, 1.5, 2];
switch (z.choose.postln,
	1,   { \no },
	1.1, { \wrong },
	1.3, { \wrong },
	1.5, { \wrong },
	2,   { \wrong },
	0,   { \true }
).postln;
)
::
or:
code::
(
var x, z;
z = [0, 1, 1.1, 1.3, 1.5, 2];
x = switch(z.choose)
	{1}   { \no }
	{1.1} { \wrong }
	{1.3} { \wrong }
	{1.5} { \wrong }
	{2}   { \wrong }
	{0}   { \true };
x.postln;
)
::

Inlined vs non-inlined comparison:

code::
(
switch(1.0)
	{ 1 } { "yes" }
	{ "no" }
)

-> no
::

The identity comparison code::1.0 === 1:: is false: while 1.0 and 1 represent the same numeric value, one is floating point and the other is an integer, so they cannot be identical.

code::
(
// 'var x' prevents inlining
switch(1.0)
	{ 1 } { var x; "yes" }
	{ "no" }
)

WARNING: Float:switch is unsafe, rounding via Float:asInteger:switch
-> yes
::


method:: case

Function implements a case method which allows for conditional evaluation with multiple cases. Since the receiver represents the first case this can be simply written as pairs of test functions and corresponding functions to be evaluated if true. Case is inlined and is therefore just as efficient as nested if statements.

discussion::
Example
code::
(
var i, x, z;
z = [0, 1, 1.1, 1.3, 1.5, 2];
i = z.choose;
x = case
	{ i == 1 }   { \no }
	{ i == 1.1 } { \wrong }
	{ i == 1.3 } { \wrong }
	{ i == 1.5 } { \wrong }
	{ i == 2 }   { \wrong }
	{ i == 0 }   { \true };
x.postln;
)
::

method:: try

Function implements a code::try:: method which allows catching exceptions thrown by code and run the exception handler. For more information see link::Classes/Exception::.
discussion::
Example
code::
try {
	...code... 
} { |error|
	...exception handler...
};
::

method:: protect

Function implements a code::protect:: method which allows protecting code from exceptions thrown by code.
The difference with code::try:: is the exception handler code is always run, even if there is no exception.
If an exception occurs, it is rethrown after the exception handler block is run.
For more information see link::Classes/Exception::.

discussion::
Example
code::
file = File(path, "r");
protect {
	// work with the file here, which might cause an error
} {
	file.close;
};
::

section:: Other Control Structures

Using Functions, many control structures can be defined like the ones above. In the class link::Classes/Collection#Iteration:: there are many more messages defined for iterating over Collections.

section:: Inline optimization

code::if::, code::while::, code::switch:: and code::case:: expressions are optimized (i.e. inlined) by the compiler if they do not contain variable declarations in the functions. The optimization plucks the code from the functions and uses a more efficient jump statement:
code::
(
{
	if(6 == 9) {
		"hello".postln;
	} {
		"world".postln;
	}
}.def.dumpByteCodes
)

BYTECODES: (20)
  0   2C 06    PushInt 6
  2   2C 09    PushInt 9
  4   E6       SendSpecialBinaryArithMsg '=='
  5   F8 00 07 JumpIfFalse 7  (15)
  8   41       PushLiteral "hello"
  9   B0       TailCallReturnFromFunction
 10   C1 3A    SendSpecialMsg 'postln'
 12   FC 00 04 JumpFwd 4  (19)
 15   40       PushLiteral "world"
 16   B0       TailCallReturnFromFunction
 17   C1 3A    SendSpecialMsg 'postln'
 19   F2       BlockReturn
-> < closed FunctionDef >
::

Failure to inline due to variable declarations:
code::
(
{
	if(6 == 9, {
		var notHere;
		"hello".postln;
	},{
		"world".postln;
	})
}.def.dumpByteCodes
)

WARNING: FunctionDef contains variable declarations and so will not be inlined.
  in file 'selected text'
  line 4 char 14:

  		var notHere;

  		"hello".postln;
-----------------------------------
BYTECODES: (13)
  0   2C 06    PushInt 6
  2   2C 09    PushInt 9
  4   E6       SendSpecialBinaryArithMsg '=='
  5   04 00    PushLiteralX instance of FunctionDef - closed
  7   04 01    PushLiteralX instance of FunctionDef - closed
  9   B0       TailCallReturnFromFunction
 10   C3 0B    SendSpecialMsg 'if'
 12   F2       BlockReturn
-> < closed FunctionDef >
::

You can switch on and off the above warning (see: link::Classes/LanguageConfig#*postInlineWarnings::)

code::
LanguageConfig.postInlineWarnings_(true) // warn
LanguageConfig.postInlineWarnings_(false) // ignore it.
::