File: Thunk.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 (54 lines) | stat: -rw-r--r-- 1,520 bytes parent folder | download | duplicates (4)
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
class::Thunk
summary::unevaluated value
categories::Core>Kernel

description::

Thunk, "past tense of think", can be used 	when a calculation may, or may not have to be performed at a later point in time, and its value is needed several times. This is an example of lazy evaluation, and can be used to avoid unnecessary calculations and to make state immutable.

classMethods::

method::new

argument::function
some function that returns the desired value

instanceMethods::

method::value

return the value. If calculation is done, use previous value, otherwise do calculation.

examples::

code::
// so for example, random values will result in a single instance:
a = Thunk({ \done.postln; rrand(2.0, 8.0) });
a.value; // posts "done"
a.value;
::

code::
// it is an AbstractFunction, so one can use it for math operations:

a = Thunk({ rrand(2.0, 8.0) });
b = a * 5 / (a - 1);
b.value;
::

code::
// lazy evaluation

a = Thunk({ \done1.postln; Array.fill(10000, { |i| i + 6 % 5 * i / 2 }) }); // some calculation.
b = Thunk({ \done2.postln;Array.fill(10000, { |i| i + 5 % 6 * i / 3 }) });// some other calculation.
c = [a, b].choose + 700;
(c * c * c).value; // calculation happens here, and only once.

// compare to a function:

a = { \done1.postln; Array.fill(10000, { |i| i + 6 % 5 * i / 2 }) }; // some calculation.
b = { \done2.postln;Array.fill(10000, { |i| i + 5 % 6 * i / 3 }) };// some other calculation.
c = [a, b].choose + 700;
(c * c * c).value; // calculation happens here, but 3 times (for each c)
::