2 summary::unevaluated value
3 categories::Core>Kernel
7 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.
14 some function that returns the desired value
20 return the value. If calculation is done, use previous value, otherwise do calculation.
25 // so for example, random values will result in a single instance:
26 a = Thunk({ \done.postln; rrand(2.0, 8.0) });
27 a.value; // posts "done"
32 // it is an AbstractFunction, so one can use it for math operations:
34 a = Thunk({ rrand(2.0, 8.0) });
42 a = Thunk({ \done1.postln; Array.fill(10000, { |i| i + 6 % 5 * i / 2 }) }); // some calculation.
43 b = Thunk({ \done2.postln;Array.fill(10000, { |i| i + 5 % 6 * i / 3 }) });// some other calculation.
44 c = [a, b].choose + 700;
45 (c * c * c).value; // caclulation happens here, and only once.
47 // compare to a function:
49 a = { \done1.postln; Array.fill(10000, { |i| i + 6 % 5 * i / 2 }) }; // some calculation.
50 b = { \done2.postln;Array.fill(10000, { |i| i + 5 % 6 * i / 3 }) };// some other calculation.
51 c = [a, b].choose + 700;
52 (c * c * c).value; // calculation happens here, but 3 times (for each c)