1---
2title: 'Strudel: live coding patterns on the Web'
3author:
4  - name: Felix Roos
5    affiliation: Unaffiliated
6    email: flix91@gmail.com
7  - name: Alex McLean
8    affiliation: Then Try This
9    email: alex@slab.org
10abstract: |
11  This paper introduces Strudel, which brings the TidalCycles approach to live coding algorithmic patterns to native JavaScript and the web. We begin by giving a little background of the first year of development, before sharing some detail about its implementation and examples of use. We go on to outline the wide range of synthesis and other outputs available in Strudel, including WebAudio, MIDI, OSC (for SuperDirt), WebSerial and CSound, and introduce Strudel's REPL live editor, including its built-in visualisations. We then compare Strudel with Tidal, the trade-offs involved between JavaScript and Haskell, and the unique capabilities offered by Strudel for aligning patterns, before concluding with some thoughts about the future.
12bibliography: citations.json
13fontsize: 11pt
14geometry: margin=2cm
15fontfamily: libertine
16fontfamily: inconsolata
17mainfont: Linux Libertine O
18monofont: Inconsolata
19date: '2022-12-14'
20---
21
22# Introduction
23
24In the following paper, we introduce *Strudel*, an alternative
25implementation of the TidalCycles (or 'Tidal' for short) live coding
26system, using the JavaScript programming language. Strudel is an
27attempt to make live coding more accessible, by creating a system that
28runs entirely in the browser, while opening Tidal's approach to
29algorithmic patterns [@mcleanAlgorithmicPattern2020a] up to modern
30audio/visual web technologies. The Strudel REPL is a live code editor
31dedicated to manipulating patterns while they play, with builtin
32visual feedback. While Strudel is written in JavaScript, the API is
33optimized for simplicity and readability by applying code
34transformations on the syntax tree level, allowing language operations
35that would otherwise be impossible. The application supports multiple
36ways to output sound, including Tone.js, Web Audio Nodes, OSC (Open
37Sound Control) messages, Web Serial, Web MIDI and Csound. The project
38is split into multiple packages, allowing granular reuse in other
39applications. Apart from TidalCycles, Strudel draws inspiration from
40many prior existing projects like TidalVortex
41[@mcleanTidalVortexZero2022], Gibber [@robertsGibberLiveCoding2012],
42Estuary [@ogbornEstuaryBrowserbasedCollaborative2017], Hydra
43[@jackHydra2022], Ocarina [@solomonPurescriptocarina2022] and
44Feedforward [@mcleanFeedforward2020]. This paper expands the Strudel
45Demo paper for the Web Audio Conference 2022 [@StrudelWAC2022].
46
47The first tentative commit to the Strudel project was on 22nd January
482022 by Alex McLean, with the core representation implemented over the
49following few days. Although this was his first attempt at a
50JavaScript-based application, by 27th January, Alex had managed to
51upload the initial version to the 'npm' javascript package database,
52sharing with the wider community for comment. By 4th February, Felix
53Roos had discovered Strudel and contributed a 'REPL' user interface to
54it, and then contributed a scheduler the next day, so that Strudel
55could already make sound.  At this point, Alex and Felix shared
56ownership to the repository, and the project has since proved to be a
57productive confluence of Felix's own work into music representation
58and visualisation, with Alex's experience with making Tidal. Felix has
59since become the primary contributor to Strudel, with Alex continuing
60to jump between developing both Strudel and Tidal. Aspects of
61Strudel's development have therefore fed back into TidalCycles, and
62both systems have maintained a shared conceptual underpinning. We plan
63to continue working towards feature parity between these systems,
64although within the syntactical trade-offs and library ecosystems of
65JavaScript and Haskell, some divergence is inevitable and healthy.
66
67Over the first year of its life, Strudel is now a fully-fledged live
68coding environment, porting Tidal's core represention of patterns,
69pattern transformations, and mini-notation for polymetric sequences,
70combined with a wealth of features for synthesising and visualising
71those patterns.
72
73# From Tidal to Strudel and back
74
75As mentioned above, the original Tidal is implemented as a domain specific language (DSL) embedded in the Haskell pure functional programming language, and takes advantage of Haskell's terse syntax and advanced, 'strong' type system. JavaScript on the other hand, is a multi-paradigm programming language, with a dynamic type system. Because Tidal leans heavily on many of Haskell's more unique features, it was not always clear that it could meaningfully be ported to a multi-paradigm scripting language. However, this possibility was already demonstrated with an earlier port to Python [TidalVortex; @mcleanTidalVortexZero2022], and we have now successfully implemented Tidal's pure functional representation of patterns in Strudel, including partial application, currying, and the functor, applicative and monadic structures that underlie Tidal's expressive pattern transformations. The result is a terse and highly composable system, where everything is either a pattern, or a function for combining and manipulating patterns, offering a rich creative ground for exploration.
76
77This development process has been far from a one-way port, however. The process of porting Tidal's concepts has also opened up new possibilities, some just from revisiting every design decision, and some from the particular affordances and constraints offered by JavaScript. This has lead to new features (and indeed bugfixes) that have found their way back to Tidal where appropriate, and ongoing work that we will return to in the conclusion of this paper.
78
79# Representing Patterns
80
81Patterns are the essence of Tidal. Its patterns are abstract entities that represent flows of time as functions, adapting a technique called pure functional reactive programming. Taking a time span as its input, a Pattern can output a set of events that happen within that time span. It depends on the structure of the Pattern how the events are located in time.
82From now on, this process of generating events from a time span will be called **querying**.
83Example:
84
85```js
86const pattern = sequence(c3, [e3, g3])
87const events = pattern.queryArc(0, 1)
88console.log(events.map(e => e.show()))
89```
90
91In this example, we create a pattern using the `sequence` function and **query** it for the time span from `0` to `1`.
92Those numbers represent units of time called **cycles**. The length of one cycle depends on the tempo, which defaults to one cycle per second.
93The resulting events are:
94
95```js
96 ["[ 0/1 -> 1/2 | c3 ]", 
97  "[ 1/2 -> 3/4 | e3 ]", 
98  "[ 3/4 -> 1/1 | g3 ]"
99 ]
100```
101
102Each event has a value, a begin time and an end time, where time is represented as a fraction. In the above case, the events are placed in sequential order, where c3 takes the first half, and e3 and g3 together take the second half. This temporal placement is the result of the `sequence` function, which divides its arguments equally over one cycle. If an argument is an array, the same rule applies to that part of the cycle. In the example, e3 and g3 are divided equally over the second half of the whole cycle.
103
104Note that the query function is not just a way to access a pattern, but true to the principles of functional programming, is the pattern itself. This means that in theory there is no way to change a pattern, it is opaque as a pure function. In practice though, Strudel and Tidal are all about transforming patterns, so how is this done? The answer is, by replacing the pattern with a new one, that calls the old one. This new one is only able to manipulate the query before passing it to the old pattern, and manipulate the results from it before returning them to caller. But, this is enough to support all the temporal and structural manipulations provided by Strudel (and Tidal's) extensive library of functions.
105
106The above examples do not represent how Strudel is used in practice. In the live coding editor, the user only has to type in the pattern itself, the querying will be handled by the scheduler. The scheduler will repeatedly query the pattern for events, which are then scheduled as sound synthesis or other event triggers.
107Also, the above event data structure has been simplified for readability.
108
109![Screenshot of the Strudel 'REPL' live coding editor, including piano-roll visualisation.](images/strudel-screenshot2.png){ width=60% }
110
111# Making Patterns
112
113In practice, the end-user live coder will not deal with constructing patterns directly, but will rather build patterns using Strudel's extensive combinator library to create, combine and transform patterns.
114
115The live coder will rarely use the `sequence` function as seen above, as sequencing is implicit in many functions. For example in the following, the `note` function constructs a pattern of notes, sequencing its arguments in the same manner as the previous example.
116
117```js
118note(c3, [e3, g3])
119```
120
121Perhaps more often, they will use the mini-notation for even terser notation of rhythmic sequences: ^[This last example is also valid Tidal code, albeit the parenthesis is not required in its Haskell syntax in this case. Tidal does not support passing sequences as lists directly to the `note` function, however.].
122
123```js
124note("c3 [e3 g3]")
125```
126
127Such sequences are often treated only as a starting point for manipulation, where they then undergo pattern transformations such as repetition, symmetry, interference/combination or randomisation, potentially at multiple timescales. Because Strudel patterns are represented as pure functions of time rather than as data structures, very long and complex generative results can be represented and manipulated without having to store the resulting sequences in memory.
128
129# Pattern Example
130
131The following example showcases how patterns can be utilized to create musical complexity from simple parts, using repetition and interference:
132
133```js
134"<0 2 [4 6](3,4,1) 3>"
135.off(1/4, add(2))
136.off(1/2, add(6))
137.scale('D minor')
138.legato(.25)
139.note().s("sawtooth square")
140.delay(.8).delaytime(.125)
141```
142
143The pattern starts with a rhythm of numbers in mini-notation, which are later interpreted inside the scale of D minor.
144The first line could also be expressed without mini-notation:
145
146```js
147cat(0, 2, [4, 6].euclid(3, 4, 1), 3)
148```
149
150These numbers then undergo various pattern transformations. Here is a short description of all the functions used:
151
152- `cat`: play elements sequentially, where each lasts one cycle
153- `brackets`: elements inside brackets are divided equally over the time of their parent
154- `.euclid(p, s, o)`: place p pulses evenly over s steps, with offset o [@toussaintEuclideanAlgorithmGenerates2005]
155- `.off(n, f)`: layers a pattern on top of itself, with the new layer offset by n cycles, and with function f applied
156- `.legato(n)`: multiply the duration of all events in a pattern by a factor of n
157- `.echo(t, n, v)`: copy each event t times, with n cycles in between each copy, decreasing velocity by v
158- `.note()`: interpretes values as notes
159- `.s(name)`: play back each event with the given sound
160- `.delay(wet)`: add delay
161- `.delaytime(t)`: set delay time
162
163Much of the above will be familiar to Tidal users.
164
165<!-- This example shows some of Strudel's unique support for chords and transposition familiar to students of Western music theory. This differs a little from Tidal's approach and thanks to the integration of the javascript library XXX (*TODO* ? or is this all your work Felix?), Strudel's support for tonal transformations such as voice leading is perhaps respects more advanced than Tidal. -->
166
167# Ways to make Sound (and other events)
168
169To generate sound, Strudel supports bindings for different outputs:
170
171- Tone.js (deprecated)
172- Web Audio API
173- WebDirt, a js recreation of Tidal's *Dirt* sample engine (deprecated)
174- OSC via osc-js, compatible with superdirt
175- Csound via the Csound WebAssembly build
176- MIDI via WebMIDI
177- Serial via WebSerial
178
179At first, we used Tone.js as sound output, but it proved to be limited for the use case of Strudel, where each individual event could potentially have a completely different audio graph.
180While the Web Audio API takes a *fire-and-forget* approach, creating a lot of Tone.js instruments and effects causes performance issues quickly. For that reason, we chose to search for alternatives.
181
182Strudel's new default output uses the Web Audio API to create a new audio graph for each event. It currently supports basic oscillators, sample playback, various effects and an experimental support for soundfonts.
183
184WebDirt [@ogbornDktr0WebDirt2022] was created as part of the Estuary Live Coding System [@ogbornEstuaryBrowserbasedCollaborative2017], and proved to be a solid choice for handling samples in Strudel as well. We are however focused on working more directly with the Web Audio API to be able to integrate new features more tightly.
185
186Using the OSC protocol via Strudel's provided Node.js-based OSC proxy server, it is possible to send network messages to trigger events. This is mainly used to render sound using SuperDirt [@SuperDirt2022], which is the well-developed Supercollider-based synthesis framework that Tidal live coders generally use as standard.
187
188Recently, the experimental integration of Csound proved to bring a new dimension of sound design capabilities to Strudel. Thanks to the WebAssembly distribution of this classic system [@CsoundWebAssembly], Csound 'orchestra' synthesisers can be embedded in and then patterned with Strudel code.
189
190MIDI output can also be used to send MIDI messages to either external instruments or to other programs on the same device. Unlike OSC, Strudel is able to send MIDI directly without requiring additional proxy software, but only from web browsers that support it (at the time of writing, this means Chromium-based browsers).
191
192Finally, Strudel supports Serial output, for example to trigger events
193via microcontrollers. This has already been explored for robot
194choreography by Kate Sicchio and Alex McLean, via a performance
195presented at the International Conference on Live Interfaces 2022.
196
197# The Strudel REPL
198
199While Strudel can be used as a library in any JavaScript codebase, its main, reference user interface is the Strudel REPL^[REPL stands for read, evaluate, print/play, loop. It is friendly jargon for an interactive programming interface from computing heritage, usually for a commandline interface but also applied to live coding editors.], which is a browser-based live coding environment. This live code editor is dedicated to manipulating Strudel patterns while they play. The REPL features built-in visual feedback, highlighting which elements in the patterned (mini-notation) sequences are influencing the event that is currently being played. This feedback is designed to support both learning and live use of Strudel.
200
201Besides a UI for playback control and meta information, the main part of the REPL interface is the code editor powered by CodeMirror. In it, the user can edit and evaluate pattern code live, using one of the available synthesis outputs to create music and/or sound art. The control flow of the REPL follows 3 basic steps:
202
2031. The user writes and updates code. Each update transpiles and evaluates it to create a `Pattern` instance
2042. While the REPL is running, the `Scheduler` queries the active `Pattern` by a regular interval, generating `Events` (also known as `Haps` in Strudel) for the next time span.
2053. For each scheduling tick, all generated `Events` are triggered by calling their `onTrigger` method, which is set by the output.
206
207![REPL control flow](images/strudelflow.png){ width=43% }
208
209## User Code
210
211To create a `Pattern` from the user code, two steps are needed:
212
2131. Transpile the JS input code to make it functional
2142. Evaluate the transpiled code
215
216### Transpilation & Evaluation
217
218In the JavaScript world, using transpilation is a common practise to be able to use language features that are not supported by the base language. Tools like `babel` will transpile code that contains unsupported language features into a version of the code without those features.
219
220In the same tradition, Strudel can add a transpilation step to simplify the user code in the context of live coding. For example, the Strudel REPL lets the user create mini-notation patterns using just double quoted strings, while single quoted strings remain what they are:
221
222```js
223"c3 [e3 g3]*2"
224```
225
226is transpiled to:
227
228```js
229mini("c3 [e3 g3]*2").withMiniLocation([1,0,0],[1,14,14])
230```
231
232Here, the string is wrapped in `mini`, which will create a pattern from a mini-notation string. Additionally, the `withMiniLocation` method passes the original source code location of the string to the pattern, which enables highlighting active events.
233
234Other convenient features like pseudo variables, operator overloading and top level await are possible with transpilation.
235
236After the transpilation, the code is ready to be evaluated into a `Pattern`.
237
238Behind the scenes, the user code string is parsed with `acorn`, turning it into an Abstract Syntax Tree (AST). The AST allows changing the structure of the code before generating the transpiled version using `escodegen`.
239
240### Mini-notation
241
242While the transpilation allows JavaScript to express Patterns in a less verbose way, it is still preferable to use the mini-notation as a more compact way to express rhythm. Strudel aims to provide the same mini-notation features and syntax as used in Tidal.
243
244The mini-notation parser is implemented using `peggy`, which allows generating performant parsers for Domain Specific Languages (DSLs) using a concise grammar notation. The generated parser turns the mini-notation string into an AST which is used to call the respective Strudel functions with the given structure. For example, `"c3 [e3 g3]*2"` will result in the following calls:
245
246```js
247seq(
248  reify('c3').withLocation([1,1,1], [1,4,4]),
249  seq(
250    reify('e3').withLocation([1,5,5], [1,8,8]),
251    reify('g3').withLocation([1,8,8], [1,10,10]),
252  ).fast(2)
253)
254```
255
256### Highlighting Locations
257
258As seen in the examples above, both the JS and the mini-notation parser add source code locations using `withMiniLocation` and `withLocation` methods. While the JS parser adds locations relative to the user code as a whole, the mini-notation adds locations relative to the position of the mini-notation string. The absolute location of elements within mini-notation can be calculated by simply adding both locations together. This absolute location can be used to highlight active events in real time.
259
260## Scheduling Events
261
262After an instance of `Pattern` is obtained from the user code,
263it is used by the scheduler to get queried for events. Once started, the scheduler runs at a fixed interval to query the active pattern for events within the current interval's time span. A simplified implementation looks like this:
264
265```js
266let pattern = seq('c3', ['e3', 'g3']); // pattern from user
267let interval = 0.5; // query interval in seconds
268let time = 0; // beginning of current time span
269let minLatency = .1; // min time before a hap should trigger
270setInterval(() => {
271  const haps = pattern.queryArc(time, time + interval);
272  time += interval; // increment time
273  haps.forEach((hap) => {
274    const deadline = hap.whole.begin - time + minLatency;
275    onTrigger(hap, deadline, duration);
276  });
277}, interval * 1000); // query each "interval" seconds
278```
279
280Note that the above code is simplified for illustrative purposes. The actual implementation has to work around imprecise callbacks of `setInterval`. More about the implementation details can be read in [this blog post](https://loophole-letters.vercel.app/web-audio-scheduling).
281
282The fact that `Pattern.queryArc` is a pure function that maps a time span to a set of events allows us to choose any interval we like without changing the resulting output. It also means that when the pattern is changed from outside, the next scheduling callback will work with the new pattern, keeping its clock running.
283
284The latency between the time the pattern is evaluated and the change is heard is between `minLatency` and `interval + minLatency`, in our example between 100ms and 600ms. In Strudel, the current query interval is 50ms with a minLatency of 100ms, meaning the latency is between 50ms and 150ms.
285
286## Output
287
288The last step is to trigger each event in the chosen output.
289This is where the given time and value of each event is used to generate audio or any other form of time based output. The default output of the Strudel REPL is the WebAudio output. To understand what an output does, we first have to understand what control parameters are.
290
291### Control Parameters
292
293To be able to manipulate multiple aspects of sound in parallel, so called control parameters are used to shape the value of each event. Example:
294
295```js
296note("c3 e3").cutoff(1000).s('sawtooth')
297  .queryArc(0, 1).map(hap => hap.value)
298/* [
299  { note: 'c3', cutoff: 1000, s: 'sawtooth' }
300  { note: 'e3', cutoff: 1000, s: 'sawtooth' }
301] */
302```
303
304Here, the control parameter functions `note`, `cutoff` and `s` are used, where each controls a different property in the value object. Each control parameter function accepts a primitive value, a list of values to be sequenced into a `Pattern`, or a `Pattern`. In the example, `note` gets a `Pattern` from a mini-notation expression (double quoted), while `cutoff` and `s` are given a `Number` and a (single quoted) `String` respectively.
305
306Strudel comes with a large default set of control parameter functions that are based on the ones used by Tidal and SuperDirt, focusing on music and audio terminology. It is however possible to create custom control parameters for any purpose:
307
308```js
309const { x, y } = createParams('x', 'y')
310x(sine.range(0, 200)).y(cosine.range(0,200))
311```
312
313This example creates the custom control parameters `x` and `y` which are then used to form a pattern that descibes the coordinates of a circle.
314
315### Outputs
316
317Now that we know how the value of an event is manipulated using control parameters, we can look at how outputs can use that value to generate anything. The scheduler above was calling the `onTrigger` function which is used to implement the output. A very simple version of the web audio output could look like this:
318
319```js
320function onTrigger(hap, deadline, duration) {
321  const { note } = hap.value;
322  const time = getAudioContext().currentTime + deadline;
323  const o = getAudioContext().createOscillator();
324  o.frequency.value = getFreq(note);
325  o.start(time);
326  o.stop(time + event.duration);
327  o.connect(getAudioContext().destination);
328}
329```
330
331The above example will create an `OscillatorNode` for each event, where the frequency is controlled by the `note` param. In essence, this is how the WebAudio API output of Strudel works, only with many more parameters to control synths, samples and effects.
332
333# Pattern alignment and combination
334
335One core aspect of Strudel, inherited from Tidal, is the flexible way that patterns can be combined, irrespective of their structure. Its declarative approach means a live coder does not have to think about the details of *how* this is done, only *what* is to be done.
336
337As a simple example, consider two number patterns `"0 [1 2] 3"`, and `"10 20"`. The first has three contiguous steps of equal lengths, with the second step broken down into two substeps, giving four events in total. There are a very large number of ways in which the structure of these two patterns could be combined, but the default method in both Strudel and Tidal is to line up the cycles of the two patterns, and then take events from the first pattern and match them with those in the second pattern. Therefore, the following two lines are equivalent:
338
339```js
340"0 [1 2] 3".add("10 20")
341"10 [11 22] 23"
342```
343
344Where the events only partially overlap, they are treated as fragments
345of the event in the first pattern. This is a little difficult to
346conceptualise, but lets start by comparing the two patterns in the
347following example:
348
349```js
350"0 1 2".add("10 20")
351"10 [11 21] 20"
352```
353
354They are similar to the previous example in that the number `1` is split in two, with its two halves added to `10` and `20` respectively. However, the `11` 'remembers' that it is a fragment of that original `1` event, and so is treated as having a duration of a third of a cycle, despite only being active for a sixth of a cycle. Likewise, the `21` is also a fragment of that original `1` event, but a fragment of its second half. Because the start of its event is missing, it wouldn't actually trigger a sound (unless it underwent further pattern transformations/combinations).
355
356In practice, the effect of this default, implicit method for combining two patterns is that the second pattern is added *in* to the first one, and indeed this can be made explicit:
357
358```js
359"0 1 2".add.in("10 20")
360```
361
362This makes way for other ways to align the pattern, and several are already defined, in particular:
363
364* `in` - as explained above, aligns cycles, and applies values from the pattern on the right *in* to the pattern on the left.
365* `out` - as with `in`, but values are applied *out* of the pattern on the left (i.e. *in* to the one on the right).
366* `mix` - structures from both patterns are combined, so that the new events are not fragments but are created at intersections of events from both sides.
367* `squeeze` - cycles from the pattern on the right are squeezed into events on the left. So that e.g. `"0 1 2".add.squeeze("10 20")` is equivalent to `"[10 20] [11 21] [12 22]"`.
368* `squeezeout` - as with `squeeze`, but cycles from the left are squeezed into events on the right. So, `"0 1 2".add.squeezeout("10 20")` is equivalent to `[10 11 12] [20 21 22]`.
369* `trig` is similar to `squeezeout` in that cycles from the right are aligned with events on the left. However those cycles are not 'squeezed', rather they are truncated to fit the event. So `"0 1 2 3 4 5 6 7".add.trig("10 [20 30]")` would be equivalent to `10 11 12 13 20 21 30 31`. In effect, events on the right 'trigger' cycles on the left.
370* `trigzero` is similar to `trig`, but the pattern is 'triggered' from its very first cycle, rather than from the current cycle. `trig` and `trigzero` therefore only give different results where the leftmost pattern differs from one cycle to the next.
371
372We will save going deeper into the background, design and practicalities of these alignment functions for future publications. However in the next section, we take them as a case study for looking at the different design affordances offered by Haskell to Tidal, and JavaScript to Strudel.
373
374# Comparing Strudel and Haskell in use
375
376Unlike Haskell, JavaScript lacks the ability to define custom infix
377operators, or change the meaning of existing ones. So the above
378Strudel example of `"0 1 2".add.out("10 20")` is equivalent to the
379Tidal expression `"0 1 2" +| "10 20"`, where the vertical bar in the
380operator `+|` stands for `out` (where `a |+ b` would be equivalent of
381`a.add.in(b)`).
382
383From this we can already see that Tidal tends towards brevity through
384mixing infix operators with functions, and Strudel tends towards
385spelling out operations which are joined together with the `.`
386operator. This then is the design trade-off of Tidal's tersity,
387versus Strudel's simplicity.
388
389To demonstrate this, consider the following Tidal pattern:
390
391```haskell
392iter 4 $ every 3 (||+ n "10 20") $ (n "0 1 3") # s "triangle" # crush 4
393```
394
395This can be directly translated to the Strudel equivalent:
396
397```js
398iter(4, every(3, add.squeeze("10 20"), n("0 1 3").s("triangle").crush(4)))
399```
400
401Although for a more canonical Strudel expression, we would reorder it
402as:
403
404```js
405n("0 1 3").every(3, add.squeeze("10 20")).iter(4).s("triangle").crush(4)
406```
407
408The Strudel example uses the `.` method call operator for all
409operations and combinations, whereas the Tidal example has `#` for the
410default method for combining patterns and uses infix operators for
411other methods. The relative lack of parenthesis in the Tidal example is partly
412due to the way that arguments are applied to Haskell's functions, and
413partly due to the use of the `$` operator as an alternative way to
414establish precedence and control the order of evaluation.
415
416Considering the above, we hypothesise that the Haskell syntax is a little
417cleaner, but that the Strudel syntax is easier to learn. Our informal
418observation is that while Haskell's dollar `$` operator is very useful
419in making code easier to work with, it is one of the most difficult
420aspects of Tidal use for beginners to learn. On the other hand, the
421deeper levels of parenthesis in Strudel code can be difficult to keep
422track of, especially while coding under pressure of live musical
423performance. However this difficulty can largely be mitigated by
424reordering expressions, and further mitigated by supporting editor
425features.
426
427With Strudel, we have little choice but to embrace the affordances and
428constraints offered by JavaScript, and while designing a
429domain-specific language based on method calls is a
430challenge, through creative adoption of functional programming
431techniques like partial application, we are so far very happy with the
432results. Tidal's functional reactive approach to pattern-making has in
433general translated well to JavaScript, and opportunities and
434constraints have overall traded off to create a very approachable and
435useable live coding environment.
436
437## The trade-off of flexible typing
438
439We have identified one problem with porting Tidal to JavaScript where we have missed Haskell's strict typing and type inference. In both Tidal and Strudel, time is rational, where any point in time is represented as the ratio of two integers. This allows representation of musical ratios such that are impossible to represent accurately using the more common floating point numbers. However while libraries are available that support rational numbers in JavaScript, the lack of strict typing means that it is easy to implement pattern methods where computationally expensive conversion from floating point to rational numbers are performed late, and therefore often enough to overload the CPUs, due to the large number of iterative calculations required to estimate a ratio for a given floating point number. To mitigate this problem, we might consider moving to TypeScript in the future.
440
441# Future Outlook
442
443The project is still young, with many features on the horizon. As general guiding principles, Strudel aims to be
444
4451. accessible
4462. consistent with Tidal's approach to pattern
4473. modular and extensible
448
449While Haskell's type system makes it a great language for the ongoing development of Tidal's inner representation of pattern, JavaScript's vibrant ecosystem, flexibility and accessibility makes it a great host for more ad-hoc experiments, including interface design. For the future, it is planned to integrate additional alternative sound engines such as Glicol [@lanChaosprintGlicol2022] and Faust [@FaustProgrammingLanguage2022]. Strudel is already approaching feature parity with Tidal, but there are more Tidal functions to be ported, and work to be done to improve compatibility with Tidal's mini-notation. Tidal version 2.0 is under development, which brings a new representation for sequences to its patterns, which will then be brought to Strudel. Besides sound, other ways to render events are being explored, such as graphical, and choreographic output. We are also looking into alternative ways of editing patterns, including multi-user editing for network music, parsing a novel syntax to escape the constraints of JavaScript, and developing hardware/e-textile interfaces. In summary, there is a lot of fun ahead.
450
451# Links
452
453The Strudel REPL is available at <https://strudel.cc>, including an interactive tutorial.
454The repository is at <https://codeberg.org/uzu/strudel>, all the code is open source under the AGPL-3.0 License.
455
456# Acknowledgments
457
458Thanks to the Strudel and wider Tidal, live coding, WebAudio and free/open source software communities for inspiration and support. Alex McLean's work on this project is supported by a UKRI Future Leaders Fellowship [grant number MR/V025260/1].
459
460# References