Classes | Core>Kernel

# Function : AbstractFunction : Object

Implements a function
Source: Function.sc
See also: FunctionDef

## Description

A Function is a reference to a FunctionDef and its defining context Frame. When a FunctionDef is encountered in your code it is pushed on the stack as a Function. A Function can be evaluated by using the 'value' method. See the Functions help file for a basic introduction.

Because it inherits from AbstractFunction, Functions respond to math operations by creating a new Function.

    // example
    (
    var a, b, c;
    a = { [100, 200, 300].choose };    // a Function
    b = { 10.rand + 1 };    // another Function
    c = a + b;     // c is a Function.
    c.value.postln;    // evaluate c and print the result
    )

See AbstractFunction for function composition examples.

Because Functions are such an important concept, here some examples from related programming languages with functions as first class objects:

    // returning the first argument itself:
    { |x| x }.value(1) // SuperCollider
    [:x | x ] value: 1 // Smalltalk
    ((lambda (x) x) 1) // Lisp

### Related Keywords

### thisFunction

The global pseudo-variable `thisFunction` always evaluates to the current enclosing Function.

NOTE: Be aware of inline optimizations which will be reflected in the value of `thisFunction`.

See also: thisFunctionDef

## Class Methods

### Inherited class methods

## Instance Methods

### Access

### .def

Get the definition ( FunctionDef ) of the Function.

### .isClosed

returns true if the function is closed, i.e. has no external references and can thus be converted to a compile string safely.

### Evaluation

### .value( ... args)

Evaluates the FunctionDef referred to by the Function. The Function is passed the args given.

    { |a, b| (a * b).postln }.value(3, 10);
    { arg a, b; (a * b).postln }.value(3, 10); // different way of expressing the same

### .valueArray( ... args)

Evaluates the FunctionDef referred to by the Function. If the last argument is an Array or List, then it is unpacked and appended to the other arguments (if any) to the Function. If the last argument is not an Array or List then this is the same as the 'value' method.

    { |a, b, c| ((a * b) + c).postln }.valueArray([3, 10, 7]);

    { |a, b, c, d| [a, b, c, d].postln }.valueArray([1, 2, 3]);

    { |a, b, c, d| [a, b, c, d].postln }.valueArray(9, [1, 2, 3]);

    { |a, b, c, d| [a, b, c, d].postln }.valueArray(9, 10, [1, 2, 3]);

A common syntactic shortcut:

    { |a, b, c| ((a * b) + c).postln }.value(*[3, 10, 7]);

### .valueEnvir( ... args)

As value above. Unsupplied argument names are looked up in the current Environment.

    (
    Environment.use({
    ~a = 3;
    ~b = 10;
    { |a, b| (a * b).postln }.valueEnvir;
    });
    )

### .valueArrayEnvir( ... args)

Evaluates the FunctionDef referred to by the Function. If the last argument is an Array or List, then it is unpacked and appended to the other arguments (if any) to the Function. If the last argument is not an Array or List then this is the same as the 'value' method. Unsupplied argument names are looked up in the current Environment.

### .valueWithEnvir(envir)

Evaluate the function, using arguments from the supplied environment This is slightly faster than valueEnvir and does not require replacing the currentEnvironment

    (
    e = Environment.make({ ~a = 3; ~b = 10 });
    { |a, b| (a * b) }.valueWithEnvir(e);
    )

### .functionPerformList(selector, arglist)

For Function, this behaves the same as valueArray(arglist). It is used where Functions and other objects should behave differently to value, such as in the object prototyping implementation of Environment.

### .performWithEnvir(selector, envir)

    a = { |a, b, c| postf("% plus % plus % is %\n", a, b, c, a + b + c); "" };
    a.performWithEnvir(\value, (a: 1, c: 3, d: 4, b: 2));

#### Arguments:

selector | A Symbol representing a method selector.
envir | The remaining arguments derived from the environment and passed as arguments to the method named by the selector.

### .performKeyValuePairs(selector, pairs)

    a = { |a, b, c| postf("% plus % plus % is %\n", a, b, c, a + b + c); "" };
    a.performKeyValuePairs(\value, [\a, 1, \b, 2, \c, 3, \d, 4]);

#### Arguments:

selector | A Symbol representing a method selector.
pairs | Array or List with key-value pairs.

### .loop

Repeat this function. Useful with Task and Clocks.

    t = Task({ { "I'm loopy".postln; 1.wait;}.loop });
    t.start;
    t.stop;

### .defer(delta)

Delay the evaluation of this Function by `delta` in seconds on AppClock.

This is equivalent to `AppClock.sched(0, function)` unless `delta` is `nil`. In that case the function is only scheduled if current code is not running on AppClock, otherwise the function is evaluated immediately.

    { "2 seconds have passed.".postln; }.defer(2);

    (
    { "chicken".postln }.defer(0); // schedules on the AppClock
    { "egg".postln }.defer // evaluates immediately
    )

    (
    fork { // schedules on a TempoClock
        { "chicken".postln }.defer // schedules on the AppClock
    };
    { "egg".postln }.defer // evaluates immediately
    )

### .dup(n: 2)

Return an Array consisting of the results of n evaluations of this Function.

    x = { 4.rand; }.dup(4);
    x.postln;

### !(n)

From superclass: Object

equivalent to dup(n)

    x = { 4.rand } ! 4;
    x.postln;

### .sum(n: 2)

return the sum of n values produced.

    { 4.rand }.sum(8);

### .choose

evaluates the function. This makes it polymorphic to SequenceableCollection, Bag and Set.

    [{ 100.rand }, [20, 30, 40]].collect(_.choose);

### .bench(print: true)

Returns the amount of time this function takes to evaluate. print is a boolean indicating whether the result is posted. The default is true.

    { 1000000.do({ 1.0.rand }); }.bench;

### .fork(clock, quant, stackSize)

Returns a Routine using the receiver as it's function, and plays it in a TempoClock.

    { 4.do({ "Threading...".postln; 1.wait;}) }.fork;

### .forkIfNeeded(clock, quant, stackSize)

If needed, creates a new Routine to evaluate the function in, if the message is called within a routine already, it simply evaluates it.

    f = { 4.do({ "Threading...".postln; 1.wait;}) };
    f.forkIfNeeded;
    { "we are now in a routine".postln; 1.wait; f.forkIfNeeded }.fork;

### .block

Break from a loop. Calls the receiver with an argument which is a function that returns from the method block. To exit the loop, call .value on the function passed in. You can pass a value to this function and that value will be returned from the block method.

    block {|break|
        100.do {|i|
            i.postln;
            if (i == 7) { break.value(999) }
        };
    }

### .thunk

Return a Thunk, which is an unevaluated value that can be used in calculations

    x = thunk { 4.rand };
    x.value;
    x.value;

### .flop

Return a function that, when evaluated with nested arguments, does multichannel expansion by evaluating the receiver function for each channel. A flopped function responds like the "map" function in languages like Lisp.

    f = { |a, b| if(a > 0) { a + b } { -inf } }.flop;
    f.value([-1, 2, 1, -3.0], [10, 1000]);
    f.value(2, 3);

### .envirFlop

like flop, but implements an environment argument passing (valueEnvir). Less efficient in generation than flop, but not a big difference in evaluation.

    f = { |a| if(a > 0) { a + 1 } { -inf } }.envirFlop;
    e = (a: [20, 40]);
    e.use { f.value }

### .inEnvir(envir)

returns an "environment-safe" function. See Environment for more details.

    // prints nil because ~a is read from topEnvironment, not e
    e = (a: "got it", f: { { ~a.postln }.defer(0.5) });
    e.use { e.f };

    // prints "got it" because { ~a.postln } is now bound to the e environment
    e = (a: "got it", f: { { ~a.postln }.inEnvir.defer(0.5) });
    e.use { e.f };

### .case( ... cases)

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. Unlike Object-switch, this is inlined and is therefore just as efficient as nested if statements.

    (
    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;
    )

### .matchItem(item)

Interface shared with other classes that implements pattern matching. See also: matchItem. Function.matchItem evaluates the function with the item as argument, expecting a Boolean as reply.

See also matchItem.

    { |x| x > 5 }.matchItem(6); // true

### .performDegreeToKey(scaleDegree, stepsPerOctave: 12, accidental: 0)

use a function as a conversion from scale degree to note number. See also SequenceableCollection and Scale

    // a strange mapping
    (
    var f = {|degree, stepsPerOctave, acc|
        (1.8 ** (degree % stepsPerOctave) + acc).postln
    };
    Pbind(
        \scale, f,
        \degree, Pseq([0, 1, 2b, 3s, 4s, 6, 14, [0, 2, 4], [1, 3, 6]], inf)
    ).play
    )

### Exception Handling

For the following two methods a return ^ inside of the receiver itself cannot be caught. Returns in methods called by the receiver are OK.

### .try(handler)

Executes the receiver. If an exception is thrown the catch function handler is executed with the error as an argument. handler itself can rethrow the error if desired.

### .protect(handler)

Executes the receiver. The cleanup function handler is executed with an error as an argument, or nil if there was no error. The error continues to be in effect.

### Audio

### .play(target, outbus: 0, fadeTime: 0.02, addAction: 'addToHead', args)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/asDefName.sc

This is probably the simplest way to get audio in SC3. It wraps the Function in a SynthDef (adding an Out ugen if needed), creates and starts a new Synth with it, and returns the Synth object. A Linen is also added to avoid clicks, which is configured to allow the resulting Synth to have its \gate argument set, or to respond to a release message. Args in the function become args in the resulting def.

    x = { |freq = 440| SinOsc.ar(freq, 0, 0.3) }.play; // this returns a Synth object;
    x.set(\freq, 880); // note you can set the freq argument
    x.defName; // the name of the resulting SynthDef (generated automatically in a cycle of 512)
    x.release(4); // fadeout over 4 seconds

Many of the examples make use of the Function.play syntax. Note that reusing such code in a SynthDef requires the addition of an Out ugen.

    // the following two lines produce equivalent results
    { SinOsc.ar(440, 0, 0.3) }.play(fadeTime: 0.0);
    SynthDef(\help_FuncPlay, { Out.ar(0, SinOsc.ar(440, 0, 0.3))}).play;

Function.play is often more convenient than SynthDef.play, particularly for short examples and quick testing. The latter does have some additional options, such as lagtimes for controls, etc. Where reuse and maximum flexibility are of greater importance, SynthDef and its various methods are usually the better choice.

#### Arguments:

target | a Node, Server, or Nil. A Server will be converted to the default group of that server. Nil will be converted to the default group of the default Server.
outbus | the output bus to play the audio out on. This is equivalent to Out.ar(outbus, theoutput). The default is 0.
fadeTime | a fadein time. The default is 0.02 seconds, which is just enough to avoid a click. This will also be the fadeout time for a release if you do not specify.
addAction | see Synth for a list of valid addActions. The default is \addToHead.
args | arguments

### .scope(numChannels, outbus: 0, fadeTime: 0.05, bufsize: 4096, zoom)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/GUI/PlusGUI/Control/server-scope.sc

As play above, and calls Server-scope to open a scope window in which to view the output.

    { FSinOsc.ar(440, 0, 0.3) }.scope(1)

#### Arguments:

numChannels | The number of channels to display in the scope window, starting from outbus. The default is 2.
outbus | The output bus to play the audio out on. This is equivalent to Out.ar(outbus, theoutput). The default is 0.
fadeTime | A fadein time. The default is 0.02 seconds, which is just enough to avoid a click.
bufsize | The size of the buffer for the ScopeView. The default is 4096.
zoom | A zoom value for the scope's X axis. Larger values show more. The default is 1.

### .plot(duration: 0.01, server, bounds, minval, maxval, separately: false)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/GUI/PlusGUI/Math/PlotView.sc

Calculates duration in seconds worth of the output of this function asynchronously, and plots it in a GUI window. Unlike play and scope it will not work with explicit Out Ugens, so your function should return a UGen or an Array of them. The plot will be calculated in realtime.

    { SinOsc.ar(440) }.plot(0.01, bounds: Window.screenBounds);

    { {|i| SinOsc.ar(1 + i)}.dup(7) }.plot(1);

#### Arguments:

duration | The duration of the function to plot in seconds. The default is 0.01.
server | The Server on which to calculate the plot. This must be running on your local machine, but does not need to be the internal server. If nil the default server will be used.
bounds | An instance of Rect or Point indicating the bounds of the plot window.
minval | the minimum value in the plot. Defaults to -1.0.
maxval | the maximum value in the plot. Defaults to 1.0.
separately | For multi channel signals, set whether to use separate value display ranges or not. a window to place the plot in. If nil, one will be created for you.

### .asBuffer(duration: 0.01, server, action, fadeTime: 0)

Calculates duration in seconds worth of the output of this function asynchronously, and returns it in a Buffer of the number of channels. This method immediately returns a buffer, which takes `duration` seconds to become filled with data asynchronously. Then the action function is called.

#### Arguments:

duration | The duration of the function to plot in seconds. The default is 0.01.
server | The server on which the function is calculated. The default is `Server.default`.
action | A function that is called when the buffer is filled. It is passed the buffer as argument.
fadeTime | A fade in and out time in seconds. Only when greater than zero, an envelope is applied to the signal to avoid clicks (default: 0).

#### Discussion:

    // record a buffer
    b = { Blip.ar(XLine.kr(10000, 4, 3) * [1, 1.2], 20) * 0.1 }.asBuffer(3, fadeTime:0.1)
    b.plot; // after 3 seconds, you can see it.
    // play the soundfile back
    { PlayBuf.ar(b.numChannels, b, LFNoise2.kr(2 ! 8).exprange(0.15, 1), loop:1).sum }.play;

### Conversion

### .asSynthDef(rates, prependArgs, outClass: 'Out', fadeTime, name)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/asDefName.sc

Returns a SynthDef based on this Function, adding a Linen and an Out ugen if needed.

#### Arguments:

rates | An Array of rates and lagtimes for the function's arguments (see SynthDef for more details).
prependArgs | arguments
outClass | The class of the output ugen as a symbol. The default is \Out.
fadeTime | a fadein time. The default is 0.
name | the name of the SynthDef

### .asDefName

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/asDefName.sc

Performs asSynthDef (see above), sends the resulting def to the local server and returns the SynthDefs name. This is asynchronous.

    x = { SinOsc.ar(440, 0, 0.3) }.asDefName; // this must complete first
    y = Synth(x);

### .asRoutine

Returns a Routine using this as its func argument.

### .r

Returns a Routine using this as its func argument.

    a = r { 5.do { |i| i.rand.yield } };
    a.nextN(8);

### .p

Returns a Prout using this as its func argument.

    a = p { 5.do { |i| i.rand.yield } };
    x = a.asStream;
    x.nextN(8);

This is useful for using ListComprehensions in Patterns:

    Pbind(\degree, p {:[x, y].postln, x<-(0..10), y<-(0..10), (x + y).isPrime }, \dur, 0.3).play;

### Inherited instance methods

### Undocumented instance methods

### .archiveAsCompileString

### .archiveAsObject

### .argNames

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/JITLib/ProxySpace/wrapForNodeProxy.sc

### .asInstr

From extension in /Users/zzk/Library/Application Support/SuperCollider/downloaded-quarks/crucial-library/Instr/instrSupport.sc

### .asInterfaceDef

From extension in /Users/zzk/Library/Application Support/SuperCollider/downloaded-quarks/crucial-library/Instr/instrSupport.sc

### .awake(beats, seconds, clock)

### .checkCanArchive

### .cmdPeriod

### .defaultArgs

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/JITLib/ProxySpace/wrapForNodeProxy.sc

### .doOnApplicationStart

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Platform/osx/ApplicationStart.sc

### .doOnCmdPeriod

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/extSystemActions.sc

### .doOnError

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/extSystemActions.sc

### .doOnServerBoot(server)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/extSystemActions.sc

### .doOnServerQuit(server)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/extSystemActions.sc

### .doOnServerTree(server)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/extSystemActions.sc

### .doOnShutDown

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/extSystemActions.sc

### .doOnStartUp

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/Control/extSystemActions.sc

### .freqscope

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/GUI/PlusGUI/Control/server-scope.sc

### .get(prevVal)

### .handleError(error)

### .iplay( ... args)

From extension in /Users/zzk/Library/Application Support/SuperCollider/downloaded-quarks/crucial-library/Instr/instrSupport.sc

### .isFunction

### .loadToFloatArray(duration: 0.01, server, action)

### .makeFlopFunc

### .numArgs

### .numVars

### .plotAudio(duration: 0.01, minval: -1, maxval: 1, server, bounds)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/GUI/PlusGUI/Math/PlotView.sc

### .postString

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/JITLib/Patterns/extFunction.sc

### .prTry

### .prepareForProxySynthDef

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/JITLib/ProxySpace/wrapForNodeProxy.sc

### .rate

From extension in /Users/zzk/Library/Application Support/SuperCollider/downloaded-quarks/crucial-library/Players/instrSupport.sc

### .scopeResponse(server, freqMode: 1, label: "Empirical Frequency response", mute: false)

From extension in /Applications/SuperCollider.app/Contents/Resources/SCClassLibrary/Common/GUI/PlusGUI/Control/scopeResponse.sc

### .set( ... args)

### .shallowCopy

### .transformEvent(event)

### .update(obj, what ... args)

### .varArgs

## Examples

### Exception Handling

    // no exception handler
    value { 8.zorg; \didnt_continue.postln; }

    try { 8.zorg } {|error| error.postln; \cleanup.postln; }; \continued.postln;

    protect { 8.zorg } {|error| error.postln; }; \didnt_continue.postln;

    try { 123.postln; 456.throw; 789.postln } {|error| [\catch, error].postln };

    try { 123.postln; 789.postln } {|error| [\catch, error].postln };

    try { 123.postln; nil.throw; 789.postln } {|error| [\catch, error].postln };

    protect { 123.postln; 456.throw; 789.postln } {|error| [\onExit, error].postln };

    protect { 123.postln; 789.postln } {|error| [\onExit, error].postln };

    (
    try {
        protect { 123.postln; 456.throw; 789.postln } {|error| [\onExit, error].postln };
    } {|error| [\catch, error].postln };
    )

    value { 123.postln; 456.throw; 789.postln }

    value { 123.postln; Error("what happened?").throw; 789.postln }

    (
    a = [\aaa, \bbb, \ccc, \ddd];
    a[1].postln;
    a[\x].postln;
    a[2].postln;
    )

    (
    try {
        a = [\aaa, \bbb, \ccc, \ddd];
        a[1].postln;
        a[\x].postln;
        a[2].postln;
    } {|error| \caught.postln; error.dump }
    )

    (
    try {
        a = [\aaa, \bbb, \ccc, \ddd];
        a[1].postln;
        a[\x].postln;
        a[2].postln;
    } {|error| \caught.postln; error.dump; error.throw }
    )

    (
    protect {
        a = [\aaa, \bbb, \ccc, \ddd];
        a[1].postln;
        a[\x].postln;
        a[2].postln;
    } {|error| \caught.postln; error.dump }
    )

helpfile source: /Applications/SuperCollider.app/Contents/Resources/HelpSource/Classes/Function.schelp
link::Classes/Function::