Previous Section | Next Section | Table of Contents | Index | Title Page

## SAL

Nyquist supports two languages: XLISP and SAL. In some sense, XLISP and SAL are the same language, but with differing syntax. This chapter describes SAL: how it works, SAL syntax and semantics, and the relationship between SAL and XLISP, and differences between Nyquist SAL and Common Music SAL.

Nyquist SAL is based on Rick Taube's SAL language, which is part of Common Music. SAL offers the power of Lisp but features a simple, Algol-like syntax. SAL is implemented in Lisp: Lisp code translates SAL into a Lisp program and uses the underlying Lisp engine to evaluate the program. Aside from the translation time, which is quite fast, SAL programs execute at about the same speed as the corresponding Lisp program. (Nyquist SAL programs run just slightly slower than XLISP because of some runtime debugging support automatically added to user programs by the SAL compiler.)

From the user's perspective, these implementation details are hidden. You can enter SAL mode from XLISP by typing `(SAL)` to the XLISP prompt. The SAL input prompt (`SAL>` ) will be displayed. From that point on, you simply type SAL commands, and they will be executed. By setting a preference in the NyquistIDE program, SAL mode will be entered automatically.

It is possible to encounter errors that will take you from the SAL interpreter to an XLISP prompt. In general, the way to get back to SAL is by typing `(top)` to get back to the top level XLISP interpreter and reset the Nyquist environment. Then type `(sal)` to restart the SAL interpreter.

### SAL Syntax and Semantics

The most unusual feature of SAL syntax is that identifiers are Lisp-like, including names such as “play-file” and even “*warp*.” In SAL, most operators must be separated from identifiers by white space. For example, `play-file` is one identifier, but `play - file` is an expression for “play minus file,” where `play` and `file` are two separate identifiers. Fortunately, no spaces are needed around commas and parentheses.

The set SAL identifiers is difficult to describe due to a number of interacting rules designed to prevent surprising or confusing code. The exact details can be found in the `symbol-token?` function in `sal-parse.lsp`. To determine if an identifier is allowed, you can also follow the following example, which tests whether `$a@` is a valid identifier:

    SAL> print type-of(quote($a@))

If this statement prints `SYMBOL`, then the quoted expression is a valid identifier. If SAL reports a "parse error" or some other type, then the quoted expression is not a valid identifier.

In SAL, whitespace (any sequence of space, newline, or tab characters) is sometimes necessary to separate lexical tokens, but otherwise, spaces and indentation are ignored. To make SAL readable, it is strongly advised that you indent SAL programs as in the examples here. The NyquistIDE program is purposely insistent about SAL indentation, so if you use it to edit SAL programs, your indentation should be both beautiful and consistent.

As in Lisp (but very unlike C or Java), comments are indicated by semicolons. Any text from an unquoted semicolon to the end of the line is ignored.

    ; this is a comment
    ; comments are ignored by the compiler
    print "Hello World" ; this is a SAL statement

As in Lisp, identifiers are translated to upper-case, making SAL case-insensitive. For example, the function name `autonorm` can be typed in lower case or as `AUTONORM`, `AutoNorm`, or even `AuToNoRm`. All forms denote the same function. The recommended approach is to write programs in all lower case.

SAL is organized around statements, most of which contain expressions. We will begin with expressions and then look at statements.

#### Expressions

##### Simple Expressions

As in XLISP, simple expressions include:

- integers (FIXNUM's), such as `1215`,
- floats (FLONUM's) such as `12.15`,
- strings (STRING's) such as `"Magna Carta"`, and
- symbols (SYMBOL's) such as `magna-carta`. A symbol with a leading colon (`:`) evaluates to itself as in Lisp. Otherwise, a symbol denotes either a local variable, a formal parameter, or a global variable. As in Lisp, variables do not have data types or type declarations. The type of a variable is determined at runtime by its value.

Additional simple expressions in SAL are:

- lists such as `{c 60 e 64}`. Note that there are no commas to separate list elements, and symbols in lists are not evaluated as variables but stand for themselves. Lists may contain numbers, booleans (which represent XLISP's `T` or `NIL`, SAL identifiers (representing XLISP symbols), strings, SAL operators (representing XLISP symbols), and nested lists.
- Booleans: SAL interprets `#t` as true and `#f` as false. (As far as the SAL compiler is concerned, `t` and `nil` are just variables. Since these are the Lisp versions of true and false, they are interchangeable with `#t` and `#f`, respectively.)

A curious property of Lisp and Sal is that false and the empty list (`nil`) are the same value. Since SAL is based on Lisp, `#f` and `{}` (the empty list) and `nil` are all equal.

##### Operators

Expressions can be formed with unary and binary operators using infix notation. The operators are:

`+`
  addition, including sounds
`-`
  subtraction, including sounds
`*`
  multiplication, including sounds
`/`
  division (due to divide-by-zero problems, does not operate on sounds)
`%`
  modulus (remainder after division)
`^`
  exponentiation
`=`
  equal (using Lisp `equal` for non-lists, and comparing lists element-by-element recursively) (Footnote 1)
  Footnotes
`!=`
  not equal
`>`
  greater than
`<`
  less than
`>=`
  greater than or equal
`<=`
  less than or equal
`~=`
  approximately equal. Numbers are approximately equal if they are within `*~=tolerance*` of each other. `*~=tolerance*` is initially 0.000001. Non-numbers are compared with the XLISP `equal` function, and lists are compared element-by-element (recursively) using `~=`. (Footnote 2)
`&`
  logical and
`|`
  logical or
`!`
  logical not (unary)
`@`
  time shift
`@@`
  time shift to absolute time
`~`
  time stretch
`~~`
  time stretch to absolute stretch factor

Again, remember that operators must be delimited from their operands using spaces or parentheses. Operator precedence is based on the following levels of precedence:

    @ @@ ~ ~~
    ^
    / *
    % - +
    ~= <= >= > ~= =
    !
    &
    |

##### Function Calls

A function call is a function name followed by zero or more comma-delimited argument expressions enclosed within parentheses:

    list()
    piano-note(2.0, c4 + interval, 100)

Some functions use named parameters, in which case the name of the argument with a colon precedes the argument expression.

    s-save(my-snd(), ny:all, "tmp.wav", play: #t, bits: 16)

##### Array Notation

An array reference is a variable identifier followed by an index expression in square brackets, e.g.:

    x[23] + y[i]

##### Conditional Values

The special operator `#?` evaluates the first argument expression. If the result is true, the second expression is evaluated and its value is returned. If false, the third expression is evaluated and returned (or false is returned if there is no third expression):

    #?(random(2) = 0, unison, major-third)
    #?(pitch >= c4, pitch - c4) ; returns false if pitch < c4

#### SAL Statements

SAL compiles and evaluates statements one at a time. You can type statements at the SAL prompt or load a file containing SAL statements. SAL statements are described below. The syntax is indicated at the beginning of each statement type description: `this font` indicates literal terms such as keywords, the italic font indicates a place-holder for some other statement or expression. Bracket [like this] indicate optional (zero or one) syntax elements, while braces with a plus {like this}+ indicate one or more occurrences of a syntax element. Braces with a star {like this}* indicate zero or more occurrences of a syntax element: { non-terminal }* is equivalent to [ {non-terminal}+ ].

##### begin and end

`begin` [with-stmt] {statement}+ `end`

A `begin`-`end` statement consists of a sequence of statements surrounded by the `begin` and `end` keywords. This form is often used for function definitions and after `then` or `else` where the syntax demands a single statement but you want to perform more than one action. Variables may be declared using an optional `with` statement immediately after `begin`. For example:

    begin
      with db = 12.0,
           linear = db-to-linear(db)
      print db, "dB represents a factor of", linear
      set scale-factor = linear
    end

##### chdir

`chdir` expression

The `chdir` statement changes the working directory. This statement is provided for compatibility with Common Music SAL, but it really should be avoided if you use NyquistIDE. The expression following the `chdir` keyword should evaluate to a string that is a directory path name. Note that literal strings themselves are valid expressions.

    chdir "/Users/rbd/tmp"

##### define variable

[`define`] `variable` name [= expression] {, name [= expression]}*

Global variables can be declared and initialized. A list of variable names, each with an optional initialization follows the `define variable` keywords. (Since `variable` is a keyword, `define` is redundant and optional in Nyquist SAL, but required in Common Music SAL.) If the initialization part is omitted, the variable is initialized to false. Global variables do not really need to be declared: just using the name implicitly creates the corresponding variable. However, it is an error to use a global variable that has not been initialized; `define variable` is a good way to introduce a variable (or constant) with an initial value into your program.

    define variable transposition = 2,
                    print-debugging-info, ; initially false
                    output-file-name = "salmon.wav"

##### define function

[`define`] `function` name `(` [parameter] {, parameter}* `)` statement

Before a function be called from an expression (as described above), it must be defined. A function definition gives the function name, a list of parameters, and a statement. When a function is called, the actual parameter expressions are evaluated from left to right and the formal parameters of the function definition are set to these values. Then, statement is evaluated.

The formal parameters may be positional parameters that are matched with actual parameters by position from left to right. Syntactically, these are symbols and these symbols are essentially local variables that exist only until statement completes or a `return` statement causes the function evaluation to end. As in Lisp, parameters are passed by value, so assigning a new value to a formal parameter has no effect on the actual value. However, lists and arrays are not copied, so internal changes to a list or array produce observable side effects.

Alternatively, formal parameters may be keyword parameters. Here the parameter is actually a pair: a keyword parameter, which is a symbol followed by a colon, and a default value, given by any expression. Within the body of the function, the keyword parameter is named by a symbol whose name matches the keyword parameter except there is no final colon.

    define function foo(x: 1, y: bar(2, 3))
        display "foo", x, y

    exec foo(x: 6, y: 7)

In this example, `x` is bound to the value 6 and `y` is bound to the value 7, so the example prints “`foo : X = 6, Y = 7`”. Note that while the keyword parameters are `x:` and `y:`, the corresponding variable names in the function body are `x` and `y`, respectively.

The parameters are meaningful only within the lexical (static) scope of statement. They are not accessible from within other functions even if they are called by this function.

Use a `begin`-`end` statement if the body of the function should contain more than one statement or you need to define local variables. Use a `return` statement to return a value from the function. If statement completes without a `return`, the value false is returned.

##### exec

`exec` expression

Unlike most other programming languages, you cannot simply type an expression as a statement. If you want to evaluate an expression, e.g. call a function, you must use an `exec` statement. The statement simply evaluates the expression. For example,

    exec set-sound-srate(22050.0) ; change default sample rate

##### if

`if` test-expr `then` true-stmt [`else` false-stmt]

An `if` statement evaluates the expression test-expr. If it is true, it evaluates the statement true-stmt. If false, the statement false-stmt is evaluated. Use a `begin`-`end` statement to evaluate more than one statement in then `then` or `else` parts.

    if x < 0 then x = -x ; x gets its absoute value

    if x > upper-bound then
      begin
        print "x too big, setting to", upper-bound
        x = upper-bound
      end
    else
      if x < lower-bound then
        begin
          print "x too small, setting to", lower-bound
          x = lower-bound
        end

Notice in this example that the `else` part is another `if` statement. An `if` may also be the `then` part of another `if`, so there could be two possible `if`'s with which to associate an `else`. An `else` clause always associates with the closest previous `if` that does not already have an `else` clause.

##### when

`when` test statement

The `when` statement is similar to `if`, but there is no `else` clause.

    when *debug-flag* print "you are here"

##### unless

`unless` test statement

The `unless` statement is similar to `when` (and `if`) but the statement is executed when the test expression is false.

    unless count = 0 set average = sum / count

##### load

`load` path-expression

The `load` command loads a file named by path-expression, which must be either a literal string or a variable name. When evauated, path-expression must result in a string path name for the file. The extension `.sal` is appended to the path if needed. To load a file, SAL interprets each statement in the file, stopping when the end of the file or an error is encountered. If the file name ends in the extension `.lsp`, the file is assumed to contain Lisp expressions, which are evaluated by the XLISP interpreter. In general, SAL files should end with the extension `.sal`.

##### loop

`loop` [with-stmt] {stepping}* {stopping}* {action}+ [finally] `end`

The `loop` statement is by far the most complex statement in SAL, but it offers great flexibility for just about any kind of iteration. The basic function of a loop is to repeatedly evaluate a sequence of action's which are statements. Before the loop begins, local variables may be declared in with-stmt, a `with` statement.

The stepping clauses do several things. They introduce and initialize additional local variables similar to the with-stmt. However, these local variables are updated to new values after the action's. In addition, some stepping clauses have associated stopping conditions, which are tested on each iteration before evaluating the action's.

There are also stopping clauses that provide additional tests to stop the iteration. These are also evaluated and tested on each iteration before evaluating the action's.

When some stepping or stopping condition causes the iteration to stop, the finally clause is evaluated (if present). Local variables and their values can still be accessed in the finally clause. After the finally clause, the `loop` statement completes.

The stepping clauses are the following:

`repeat` expression
  Sets the number of iterations to the value of expression, which should be an integer (FIXNUM).
`for` var = expression [ `then` expr2 ]
  Introduces a new local variable named var and initializes it to expression. Before each subsequent iteration, var is set to the value of expr2. If the `then` part is omitted, expression is re-evaluated and assigned to var on each subsequent iteration. Note that this differs from a with-stmt where expressions are evaluated and variables are only assigned their values once. Warning: All `for` clauses evaluate before stopping conditions are evaluated, which means if the loop iterates N times, the `for` clauses run N+1 times. To avoid evaluation after the last iteration, you can often use `set` var = expr2.
`for` var `in` expression
  Evaluates expression to obtain a list and creates a new local variable initialized to the first element of the list. After each iteration, var is assigned the next element of the list. Iteration stops when var has assumed all values from the list. If the list is initially empty, the loop action's are not evaluated (there are zero iterations).
`for` var [`from` from-expr] [[`to` | `below` | `downto` | `above`] to-expr] [`by` step-expr]
  Introduces a new local variable named var and intialized to the value of the expression from-expr (with a default value of 0). After each iteration of the loop, var is incremented by the value of step-expr (with a default value of 1). The iteration ends when var is greater than the value of to-expr if there is a `to` clause, greater than or equal to the value of to-expr if there is a `below` clause, less than the value of to-expr if there is a `downto` clause, or less than or equal to the value of to-expr if there is a `above` clause. (In the cases of downto and above, the default increment value is -1. If there is no `to`, `below`, `downto`, or `above` clause, no iteration stop test is created for this stepping clause.

The stopping clauses are the following:

`while` expression
  The iterations are stopped when expression evaluates to false. Anything not false is considered to mean true.
`until` expression
  The iterations are stopped when expression evaluates to true.

The finally clause is defined as follows:

`finally` statement
  The statement is evaluated when one of the stepping or stopping clauses ends the loop. As always, statement may be a `begin`-`end` statement. If an action evaluates a `return` statement, the `finally` statement is not executed.

Loops often fall into common patterns, such as iterating a fixed number of times, performing an operation on some range of integers, collecting results in a list, and linearly searching for a solution. These forms are illustrated in the examples below.

    ; iterate 10 times
    loop
      repeat 10
      print random(100)
    end

    ; print even numbers from 10 to 20
    ; note that 20 is printed. On the next iteration,
    ;   i = 22, so i >= 22, so the loop exits.
    loop
      for i from 10 below 22 by 2
      print i
    end

    ; collect even numbers in a list
    loop
      with lis
      for i from 0 to 10 by 2
      set lis @= i ; push integers on front of list,
                   ; which is much faster than append,
                   ; but list is built in reverse
      finally set result = reverse(lis)
    end
    ; since "to" is used, the loop stops when i > 10
    ; now, the variable result has a list of evens: {0 2 4 6 8 10}

    ; find the first even number in a list
    result = #f ; #f means "false"
    loop
      for elem in lis
      until evenp(elem)
      finally result = elem
    end
    ; result has first even value in lis (or it is #f)

##### play

`play` expr

The `play` statement plays the sound denoted by expr, an expression.

##### plot

`plot` expr {, dur, n}

The `plot` statement plots the sound denoted by expr, an expression. If you plot a long sound, the `plot` statement will by default truncate the sound to 2.0 seconds and resample the signal to 1000 points. The optional dur is an expression that specifies the (maximum) duration to be plotted, and the optional n specifies the number of points to be plotted. Executing a `plot` statement is equivalent to calling the `s-plot` function (see Section Sound File Input and Output).

##### print

`print` expr {, expr}*

The `print` statement prints the values separated by spaces and followed by a newline. [Note that in the original SAL, the newline is printed before the values, not after.]

##### display

`display` string {, expression}*

The `display` statement is handy for debugging. At present, it is only implemented in Nyquist SAL. When executed, `display` prints the string followed by a colon and then, for each expression, the expression and its value are printed; after the last expression, a newline is printed. For example,

    display "In function foo", bar, baz

prints

    In function foo : bar = 23, baz = 5.3

SAL may print the expressions using Lisp syntax, e.g. if the expression is “bar + baz,” do not be surprised if the output is “`(sum bar baz) = 28.3`.”

    print "The value of x is", x

##### return

`return` expression

The `return` statement can only be used inside a function. It evaluates expression and then the function returns the value of the expression to its caller.

##### set

`set` var op expression {, var op expression}*

The `set` statement changes the value of a variable var according to the operator op and the value of the expression. The operators are:

`=`
  The value of expression is assigned to var.
`+=`
  The value of expression is added to var.
`*=`
  The value of var is multiplied by the value of the expression.
`&=`
  The value of expression is inserted as the last element of the list referenced by var. If var is the empty list (denoted by `#f`), then var is assigned a newly constructed list of one element, the value of expression.
`^=`
  The value of expression, a list, is appended to the list referenced by var. If var is the empty list (denoted by `#f`), then var is assigned the (list) value of expression.
`@=`
  Pushes the value of expression onto the front of the list referenced by var. If var is empty (denoted by `#f`), then var is assigned a newly constructed list of one element, the value of expression.
`<=`
  Sets the new value of var to the minimum of the old value of var and the value of expression.
`>=`
  Sets the new value of var to the maximum of the old value of var and the value of expression.

    ; example from Rick Taube's SAL description
    loop
      with a, b = 0, c = 1, d = {}, e = {}, f = -1, g = 0
      for i below 5
      set a = i, b += 1, c *= 2, d &= i, e @= i, f <= i, g >= i
      finally display "results", a, b, c, d, e, f, g
    end

##### with

`with` var [= expression] {, var [= expression]}*

The `with` statement declares and initializes local variables. It can appear only after `begin` or `loop`. If the expression is omitted, the initial value is false. The variables are visible only inside the `begin`-`end` or `loop` statement where the `with` statement appears. Even in `loop`'s the variables are intialized only when the loop is entered, not on each iteration.

##### exit

`exit` [`nyquist`]

The `exit` statement is unique to Nyquist SAL. It returns from SAL mode to the XLISP interpreter. (Return to SAL mode by typing “`(sal)`”). If `nyquist` is included in the statement, then the entire Nyquist process will exit.

### Interoperability of SAL and XLISP

When SAL evaluatas command or loads files, it translates SAL into XLISP. You can think of SAL as a program that translates everything you write into XLISP and entering it for you. Thus, when you define a SAL function, the function actually exists as an XLISP function (created using Lisp's `defun` special form). When you set or evaluate global variables in SAL, these are exactly the same Lisp global variables. Thus, XLISP functions can call SAL functions and vice-versa. At run time, everything is Lisp.

#### Function Calls

In general, there is a very simple translation from SAL to Lisp syntax and back. A function call is SAL, for example,

    osc(g4, 2.0)

is translated to Lisp by moving the open parenthesis in front of the function name and removing the commas:

    (osc g4 2.0)

Similarly, if you want to translate a Lisp function call to SAL, just reverse the translation.

#### Symbols and Functions

SAL translates keywords with trailing colons (such as `foo:`) into Lisp keywords with leading colons (such as `:foo`), but SAL keywords are not treated as expressions as they are in Lisp. You cannot write `open("myfile.txt", direction: output:)` because SAL expects an expression after direction. A special form `keyword` is defined to generate a Lisp keyword as an expression. The argument is the keyword without a colon, e.g. `open("myfile.txt", direction: keyword(output))`. Alternatively, you can write the Lisp-style keyword with the leading colon, e.g. `open("myfile.txt", direction: :output)`.

In Nyquist SAL, the hash character (#), can be used as a prefix to a Lisp function name. For example, the following command is not legal because `print` is a SAL command name, not a legal function name:

    set v = append(print(a), print(b))

(Here the intent is to print arguments to append). However, you can use the hash character to access the Lisp `print` function:

    set v = append(#print(a), #print(b))

#### Playing Tricks On the SAL Compiler

In many cases, the close coupling between SAL and XLISP gives SAL unexpected expressive power. A good example is `seqrep`. This is a special looping construct in Nyquist, implemented as a macro in XLISP. In Lisp, you would write something like:

    (seqrep (i 10) (pluck c4))

One might expect SAL would have to define a special `seqrep` statement to express this, but since statements do not return values, this approach would be problematic. The solution (which is already fully implemented in Nyquist) is to define a new macro `sal-seqrep` that is equivalent to `seqrep` except that it is called as follows:

    (sal-seqrep i 10 (pluck c4))

The SAL compiler automatically translates the identifier `seqrep` to `sal-seqrep`. Now, in SAL, you can just write

    seqrep(i, 10, pluck(c4))

which is translated in a pretty much semantics-unaware fashion to

    (sal-seqrep i 10 (pluck c4))

and viola!, we have Nyquist control constructs in SAL even though SAL is completely unaware that `seqrep` is actually a special form.

Previous Section | Next Section | Table of Contents | Index | Title Page