Pattern : AbstractFunction : Object

abstract class that holds a list


Patterns versus Streams

Pattern is an abstract class that is the base for the Patterns library. These classes form a rich and concise score language for music. The series of help files entitled Understanding Streams, Patterns and Events - Part 1 gives a detailed introduction. This attempts a briefer characterization.

A Stream is an object that responds to next, reset, and embedInStream. Streams represent sequences of values that are obtained one at a time by with message next. A reset message will cause the stream to restart (many but not all streams actually repeat themselves.) If a stream runs out of values it returns nil in response to next. The message embedInStream allows a stream definition to allow another stream to "take over control" of the stream. All objects respond to next and reset, most by returning themselves in response to next. Thus, the number 7 defines a Stream that produces an infinite sequence of 7's. Most objects respond to embedInStream with a singleton Stream that returns the object once.

A Pattern is an object that responds to asStream and embedInStream. A Pattern defines the behavior of a Stream and creates such streams in response to the messages asStream. The difference between a Pattern and a Stream is similar to the difference between a score and a performance of that score or a class and an instance of that class. All objects respond to this interface, most by returning themselves. So most objects are patterns that define streams that are an infinite sequence of the object and embed as singleton streams of that object returned once.

Patterns are defined in terms of other Patterns rather than in terms of specific values. This allows a Pattern of arbitrary complexity to be substituted for a single value anywhere within a Pattern definition. A comparison between a Stream definition and a Pattern will help illustrate the usefulness of Patterns.

example 1 - Pseq vs. Routine

The Pattern class Pseq(array, repetitions) defines a Pattern that will create a Stream that iterates an array. The class Routine(func, stackSize) defines a single Stream, the function that runs within that stream is defined to perform the array iteration.

Below a stream is created with Pseq and an asStream message and an identical stream is created directly using Routine.

// a Routine vs a Pattern
    a = [-100, 00, 300, 400];            // the array to iterate

    p = Pseq(a);                    // make the Pattern
    q = p.asStream;                    // have the Pattern make a Stream
    r = Routine({{ arg v; v.yield}) }) ;    // make the Stream directly{ Post << << << " " << <<; });

example 2 - Nesting patterns

In example 1, there is little difference between using Pseq and Routine. But Pseq actually iterates its array as a collection of patterns to be embedded, allowing another Pseq to replace any of the values in the array. The Routine, on the other hand, needs to be completely redefined.

    var routinesA;
    a = [3, Pseq([-100, 00, 300, 400]), Pseq([-100, 00, 300, 400].reverse) ];
    routinesA = [[3], [-100, 00, 300, 400], [-100, 00, 300, 400].reverse];
    p = Pseq(a);
    q = p.asStream;

    r = Routine({{ arg v;
  { arg i; i.yield})
        }) ;
    });{ Post << << << " " << <<; });

example 3 - Stream-embedInStream

The message embedInStream is what allows Patterns to do this kind of nesting. Most objects (such as the number 3 below) respond to embedInStream by yielding themselves once and returning. Streams respond to embedInStream by iterating themselves to completion, effectively "taking over" the calling stream for that time.

A Routine can perform a pattern simply by replacing calls to yield with calls to embedInStream.

    a = [3, Pseq([-100, 00, 300, 400]), Pseq([-100, 00, 300, 400].reverse) ];

    r = Routine({{ arg v; v.embedInStream}) }) ;
    p = Pseq(a);
    q = p.asStream;{ Post << << << " " << <<; });

Of course, there is no concise way to define this stream without using Pseq.

NOTE: For reasons of efficiency, the implementation of embedInStream assumes that it is called from within a Routine. Consequently, embedInStream should never be called from within the function that defines a FuncStream or a Pfunc (the pattern that creates FuncStreams).

Event Patterns

An Event is a Environment with a 'play' method. Typically, an Event consists of a collection of key/value pairs that determine what the play method actually does. The values may be any object including functions defined in terms of other named attributes. Changing those values can generate a succession of sounds sometimes called 'music'... The pattern Pbind connects specific patterns with specific names. Consult its help page for details.

Playing Event Patterns

The -play method does not return the pattern itself. Instead, it returns the EventStreamPlayer object that actually runs the pattern. Control instructions -- stop, pause, resume, play, reset -- should be addressed to the EventStreamPlayer. (The same pattern can play many times simultaneously, using different EventStreamPlayers.)

p = Pbind(...);;
p.stop;    // does not stop because p is not the EventStreamPlayer that is actually playing

p = Pbind(...).play;
p.stop;    // DOES stop because p is the EventStreamPlayer

Recording Event Patterns

Patterns may be recorded in realtime or non-realtime. See the method -record for realtime recording.

For non-realtime recording see the Score helpfile, especially "creating Score from a pattern." It can be tricky, because NRT recording launches a new server instance. That server instance is not aware of buffers or other resources loaded into the realtime server you might have been using for tests. The pattern is responsible for (re)loading any resources (buffers, effects etc.). Pfset or Pproto may be useful.

Class Methods

Inherited class methods

Instance Methods


Return a Stream from this pattern. One pattern can be used to produce any number of independent streams.

a = Pgeom(1, Pwhite(1.01, 1.2), inf);
b = a.asStream; c = a.asStream;;;;; // c is independent from b;


Given a Stream like e.g. Routine, yield all values from this pattern before continuing. One pattern can be used to produce values for any number of independent streams.



The inval is passed into all substreams and can be used to control how they behave from the outside.

a = Pgeom(1, Pwhite(1.01, 1.2), 5);
r = Routine { 2.yield; 3.yield; a.embedInStream; 7.yield; };
r.nextN(12); // the next 12 values from r

.play(clock, protoEvent, quant)



The tempo clock that will run the pattern. If omitted, TempoClock.default is used.


The event prototype that will be fed into the pattern stream on each iteration. If omitted, event.default is used.


see the Quant helpfile.

.record(path, headerFormat: "AIFF", sampleFormat: "float", numChannels: 2, dur, fadeTime: 0.2, clock, protoEvent, server, out: 0, outNumChannels)

Opens a disk file for recording and plays the pattern into it.



Disk location for the recorded file. If not given, a filename is generated for you and placed in the default recording directory: thisProcess.platform.recordingsDir.


File format, default "AIFF" - see SoundFile for supported header and sample formats.


Sample format, default "float".


Number of channels to record, default 2.


How long to run the pattern before stopping. If nil (default), the pattern will run until it finishes on its own; then recording stops. Or, use cmd-period to stop the recording. If a number is given, the pattern will run for that many beats and then stop (using Pfindur), ending the recording as well.


How many beats to allow after the last event before stopping the recording. Default = 0.2.


Which clock to use for play. Uses TempoClock.default if not otherwise specified.


Which event prototype to use for play. Falls back to Event.default if not otherwise specified.


Which server to play and record. Server.default if not otherwise specified.


Output bus to hear the pattern while recording, default = 0.


the number of out channels to play to the recorder. If larger than numChannels, outNumChannels will wrap .

Inherited instance methods

Undocumented instance methods





.asScore(duration: 1, timeOffset: 0, protoEvent)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/asScore/

.buildForProxy(proxy, channelOffset: 0)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/JITLib/ProxySpace/



.composeBinaryOp(operator, pattern, adverb)

.composeNAryOp(selector, argList)








.fin(n: 1)

.finDur(dur, tolerance: 0.001)

.flatten(n: 1)







.lock(n: 1)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/JITLib/Patterns/



From extension in /usr/local/share/SuperCollider/SCClassLibrary/JITLib/ProxySpace/


.repeat(n: inf)

.reverseComposeBinaryOp(operator, pattern, adverb)






.trace(key, printStream, prefix: "")


Below are brief examples for most of the classes derived from Pattern. These examples all rely on the patterns assigned to the Interpreter variable p, q, and r in the first block of code.


SynthDef(\cfstring1, { arg i_out, freq = 360, gate = 1, pan, amp=0.1;
    var out, eg, fc, osc, a, b, w;
    fc =, 0.4)), -1, 1, 500, 2000);
    osc = Mix.fill(8, { * [Rand(0.99, 1.01), Rand(0.99, 1.01)], 0, amp) }).distort * 0.2;
    eg =, 1, 1), gate, doneAction: Done.freeSelf);
    out = eg *, fc, 0.1);
    #a, b = out;,, [a, b], [pan, pan+0.3])));

    { arg out=0, freq=440, sustain=0.05, pan;
        var env;
        env =, sustain, 0.3), doneAction: Done.freeSelf);,, 0, env), pan))

p = Pbind(
    [\degree, \dur], Pseq([[0, 0.1], [2, 0.1], [3, 0.1], [4, 0.1], [5, 0.8]], 1),
    \amp, 0.05, \octave, 6, \instrument, \cfstring1, \mtranspose, 0);

q = Pbindf(p, \instrument, \default );

r = Pset(\freq, Pseq([500, 600, 700], 2), q);


EVENT PATTERNS - patterns that generate or require event streams

// Pbind( ArrayOfPatternPairs )

p = Pbind(
    [\degree, \dur], Pseq([[0, 0.1], [2, 0.1], [3, 0.1], [4, 0.1], [5, 0.8]], 1),
    \amp, 0.05, \octave, 6, \instrument, \cfstring1, \mtranspose, 0);;

//Ppar(arrayOfPatterns, repeats) - play in parallel

Ppar([Pseq([p], 4), Pseq([Pbindf(q, \ctranspose, -24)], 5)]).play

//Ptpar(arrayOfTimePatternPairs, repeats) - play in parallel at different times

Ptpar([1, Pseq([p], 4), 0, Pseq([Pbindf(q, \ctranspose, -24)], 5)]).play

// Pbindf( pattern, ArrayOfNamePatternPairs )

q = Pbindf(p, \instrument, \default );;

//Pfset(function, pattern)
// function constructs an event that is passed to the pattern.asStream

Pfset({ ~freq = Pseq([500, 600, 700], 2).asStream }, q).play;

//Pset(name, valPattern, pattern)
// set one field of the event on an event by event basis (Pmul, Padd are similar)

Pset(\freq, Pseq([500, 600, 700], 2), q).play;

//Psetp(name, valPattern, pattern)
// set once for each iteration of the pattern (Pmulp, Paddp are similar)

r = Pset(\freq, Pseq([500, 600, 700], 2), q);

Psetp(\legato, Pseq([0.01, 1.1], inf), r).play;

//Psetpre(name, valPattern, pattern)
// set before passing the event to the pattern (Pmulpre, Paddpre are similar)

r = Psetpre(\freq, Pseq([500, 600, 700], 2), q);

Psetp(\legato, Pseq([0.01, 1.1], inf), r).play;

//Pstretch(valPattern, pattern)
// stretches durations after

r = Psetpre(\freq, Pseq([500, 600, 700], 2), q);

Pstretch(Pn(Env([0.5, 2, 0.5], [10, 10])), Pn(r)).play;

Pset(\stretch, Pn(Env([0.5, 2, 0.5], [10, 10]) ), Pn(r)).play

//Pstretchp(valPattern, pattern)
// stretches durations after

r = Psetpre(\freq, Pseq([500, 600, 700], 2), q);

Pstretchp(Pn(Env([0.5, 2, 0.5], [10, 10])), r).play;

// Pfindur( duration, pattern ) - play pattern for duration

Pfindur(2, Pn(q, inf)).play;

// PfadeIn( pattern, fadeTime, holdTime, tolerance )
PfadeIn(Pn(q), 3, 0).play(quant: 0);

// PfadeOut( pattern, fadeTime, holdTime, tolerance )
PfadeOut(Pn(q), 3, 0).play(quant: 0);

// Psync( pattern, quantization, dur, tolerance )
// pattern is played for dur seconds (within tolerance), then a rest is played so the next pattern

    Pbind(\dur, Pwhite(0.2, 0.5).round(0.2),
        \db, Pseq([-10, -15, -15, -15, -15, -15, -30])
    ), 2, 3

//Plag(duration, pattern)

Ppar([Plag(1.2, Pn(p, 4)), Pn(Pbindf(q, \ctranspose, -24), 5)]).play

GENERAL PATTERNS that work with both event and value streams

//Ptrace(pattern, key, printStream) - print the contents of a pattern

r = Psetpre(\freq, Pseq([500, 600, 700], 2), q);

Ptrace(r, \freq).play;

{ var printStream;
    printStream =;
    Pseq([Ptrace(r, \freq, printStream), Pfunc({printStream.collection.dump; nil }) ]).play;

//Pseed(seed, pattern) - set the seed of the random number generator
// to force repetion of pseudo-random patterns

Pn(Pseed(44, Pbindf(q, \ctranspose, Pbrown(-3.0, 3.0, 10) ) ) ).play;

//Prout(function) - on exit, the function must return the last value returned by yield
// (otherwise, the pattern cannot be reliably manipulated by other patterns)

Prout({ arg inval;
    inval = p.embedInStream(inval);
    inval = Event.silent(4).yield;
    inval = q.embedInStream(inval);
    inval = r.embedInStream(inval);

//Pfunc(function) - the function should not have calls to embedInStream, use Prout instead.

Pn(Pbindf(q, \legato, Pfunc({ arg inval; if (\degree)== 5) {4} {0.2}; })) ).play

// the following patterns control the sequencing and repetition of other patterns

//Pseq(arrayOfPatterns, repeats) - play as a sequence

Pseq([Pseq([p], 4), Pseq([Pbindf(q, \ctranspose, -24)], 5)]).play

//Pser(arrayOfPatterns, num) - play num patterns from the arrayOfPatterns

Pser([p, q, r], 5).play

//Place(arrayOfPatterns, repeats) - similar to Pseq
// but array elements that are themselves arrays are iterated
// embedding the first element on the first repetition, second on the second, etc

Place([[p, q, r], q, r], 5).play

// Pn( pattern, patternRepetitions ) - repeat the pattern n times

Pn(p, 2).play;

// Pfin( eventcount, pattern ) - play n events from the pattern

Pfin(12, Pn(p, inf)).play;

// Pstutter( eventRepetitions, pattern ) - repeat each event from the pattern n times

Pstutter(4, q).play

//Pwhile(function, pattern)

Pwhile({coin(0.5).postln;}, q).play

// Pswitch( patternList, selectPattern ) - when a pattern ends, switch according to select

Pswitch([p, q, r], Pwhite(0, 100)).play

// Pswitch1( patternList, selectPattern ) - on each event switch according to select

Pn(Pswitch1([p, q, r], Pwhite(0, 2))).play

// Prand( patternList, repeats ) - random selection from list
Prand([p, q, r], inf).play

// Pxrand( patternList, repeats ) - random selection from list without repeats
Pxrand([p, q, r], inf).play

// Pwrand( patternList, weights, repeats ) - weighted random selection from list
Pwrand([p, q, r], #[1, 3, 5].normalizeSum, inf).play

// Pwalk( patternList, stepPattern, directionPattern ) - walk through a list of patterns

Pwalk([p, q, r], 1, Pseq([-1, 1], inf)).play

// Pslide(list, repeats, length, step, start)

Pbind(\degree, Pslide(#[1, 2, 3, 4, 5], inf, 3, 1, 0), \dur, 0.2).play

// Pshuf( patternList, repeats ) - random selection from list
Pn(Pshuf([p, q, r, r, p])).play

// Ptuple(list, repeats)

Pbind(\degree, Ptuple([Pwhite(1, -6), Pbrown(8, 15, 2)]),
    \dur, Pfunc({ arg ev;\degree).last/80 round: 0.1}),
    \db, Pfunc({ if (coin(0.8)) {-25} {-20} })

// the following patterns can alter the values returned by other patterns

//Pcollect(function, pattern)

Pcollect({ arg inval; inval.use({ ~freq = 1000.rand }); inval}, q).play

//Pselect(function, pattern)

Pselect({ arg inval;\degree) != 0 }, q).play(quant: 0)

//Preject(function, pattern)

Preject({ arg inval;\degree) != 0 }, q).play(quant: 0)

//Ppatmod(pattern, function, repeats) -
// function receives the current pattern as an argument and returns the next pattern to be played

Ppatmod(p, { arg oldPat; [p, q, r].choose }, inf).play

VALUE PATTERNS: these patterns define or act on streams of numbers

// Env as a pattern

Pbindf(Pn(q, inf), \ctranspose, Pn(Env.linen(3, 0, 0.3, 20), inf) ).play;

// Pwhite(lo, hi, length)

Pbindf(Pn(q, inf), \ctranspose, Pwhite(-3.0, 3.0) ).play;

// Pbrown(lo, hi, step, length)

Pbindf(Pn(q, inf), \ctranspose, Pbrown(-3.0, 3.0, 2) ).play;

// Pseries(start, step, length)

Pbindf(Pn(q, inf), \ctranspose, Pseries(0, 0.1, 10) ).play;

// Pgeom(start, step, length)

Pbindf(Pn(q, inf), \ctranspose, Pgeom(1, 1.2, 20) ).play;

// Pwrap(pattern, lo, hi)

Pbind(\note, Pwrap(Pwhite(0, 128), 10, 20).round(2), \dur, 0.05).play;

// PdegreeToKey(pattern, scale, stepsPerOctave)
// this reimplements part of pitchEvent (see Event)

Pbindf(Pn(q, inf), \note, PdegreeToKey(Pbrown(-8, 8, 2), [0, 2, 4, 5, 7, 9, 11]) ).play;

// Prewrite(pattern, dict, levels) - see help page for details.
// (notice use of Env to define a chord progression of sorts...

    Prewrite(0, ( 0: #[2, 0],
            1: #[0, 0, 1],
            2: #[1, 0, 1]
        ), 4
    ) + Pn(Env([4, 0, 1, 4, 3, 4], [6.4, 6.4, 6.4, 6.4, 6.4], 'step')),
    \dur, 0.2).play

// PdurStutter( repetitionPattern, patternOfDurations ) -
Pbindf(Pn(q), \dur, PdurStutter(
    Pseq(#[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 4, 5, 7, 15], inf),
    Pseq(#[0.5], inf)

// Pstep2add( pat1, pat2 )
// Pstep3add( pat1, pat2, pat3 )
// PstepNadd(pat1, pat2, ...)
// PstepNfunc(function, patternArray )
// combine multiple patterns with depth first traversal

    \octave, 4,
    \degree, PstepNadd(
        Pseq([1, 2, 3]),
        Pseq([0, -2, [1, 3], -5]),
        Pshuf([1, 0, 3, 0], 2)
    \dur, PstepNadd(
        Pseq([1, 0, 0, 1], 2),
        Pshuf([1, 1, 2, 1], 2)
    ).loop * (1/8),
    \legato, Pn(Pshuf([0.2, 0.2, 0.2, 0.5, 0.5, 1.6, 1.4], 4), inf),
    \scale, #[0, 1, 3, 4, 5, 7, 8]