Nu Operators
Nu includes many useful built-in operators; here is a list of them.
- Assignment
- Arithmetic and Logical
- List Processing
- Evaluation
- Control Flow
- Functions
- Macros
- Classes and Methods
- Exception Handling
- Thread Control
- System
Assignment Operators
set assigns a value to a symbol. Assignments may have global, local, or instance-specific scope, depending on the leading character of the name.
- Assignments to names beginning with '$' are given global scope. Globally-assigned values are placed in slots in the underlying symbol representation.
- Assignments to names beginning with '@' are given instance-specific scope. These are instance variables.
- All other assignments have local scope. Locally-scoped assignments are maintained in dictionaries (instances of NSMutableDictionary) that are called contexts.
(set x 22)
global assigns a value to a symbol with a forced global scope. This allows global values to be set for names that do not begin with '$'.
(global Foo "foo")
let creates a new context, makes a specified set of assignments within that context, and then evaluates a sequence of instructions in that same context.
(let ((x 2) (y 3)) (+ x y))
Arithmetic and Logical Operators
Operator | Function |
---|---|
+ - * / | basic arithmetic |
& | | bitwise logical |
> < >= <= == != eq | comparison |
<< >> | shift |
and or not | logical |
Telling truth
Several operators test values for truth. In Nu, any object that is not nil (the empty list) or 0 is considered to be true. The symbol t is also defined as a general-purpose "true" value. The value of t is itself. It is as if we had said:
(global t 't)
List Processing Operators
list evaluates its arguments and constructs a list of the results.
cons evaluates its arguments and creates a new list with the evaluated first argument at the head and the evaluated second argument as the tail.
car and head return the first element of a list.
cdr and tail return the rest of a list after the first element has been removed.
The following example constructs a list that has the same structure as mylist
:
(cons (car mylist) (cdr mylist))
The last element of a list is a special value called nil.
In Nu, nil is represented by the singleton instance [NSNull null]
. The following operations are equivalent:
(list 1 2 3) (cons 1 (cons 2 (cons 3 nil)))
append joins two lists together to form a new list. The arguments are unchanged.
% (set a '(1 2)) (1 2) % (set b '(3 4)) (3 4) % (append a b) (1 2 3 4) % a (1 2)
atom returns true if an element is not a list.
(atom nil)
also returns false, which is represented with nil.
nil is displayed as an empty list,
().
Evaluation Operators
quote prevents the evaluation of its argument. A single quote symbol is an abbreviated synonym for quote.
(quote (1 2 3)) '(1 2 3)
eval causes its argument to be evaluated.
(eval (quote (+ 2 2)))
parse parses a string containing Nu source code into a list structure.
(parse "(+ 2 2)")
context returns the current execution context (an NSMutableDictionary).
Control Flow Operators
Conditional Operators
cond scans through a list of lists, evaluating the first member of each list. When one evaluates true, the remainder of that list is evaluated and the result of the last evaluation is returned. If none evaluate true, the last list in the list of lists is evaluated. Since the last clause is always evaluated, it is conventional but not required for it to begin with the else keyword.
(cond ((eq x 1) (puts "x is 1")) ((eq x 2) (puts "x is 2")) (else (puts "x is something else")))
case tests an expression against a sequence of values, each at the head of a list. When the expression matches a value, the rest of that value's list is evaluated and the result of the last evaluation is returned. If none of the values match, the last list in the list of lists is evaluated. Since the last clause is always evaluated, it is conventional but not required for it to begin with the else keyword.
(case x (1 (puts "x is 1")) (2 (puts "x is 2")) (else (puts "x is something else")))
if tests an expression. If it evaluates true, the rest of the expressions that follow are evaluated, except for any expressions in a list beginning with the else symbol. These expressions will be evaluated if the expression evaluates false.
(if (eq x 1) (puts "x is 1") (puts "i'm sure it is") (else (puts "x is not 1")))
As a convenience, expressions can be grouped into lists that begin with the then symbol.
(if (eq x 1) (then (puts "x is 1")) (else (if (eq x 2) (then (puts "x is 2")) (else (puts "x is something else")))))
unless can be seen as the opposite
of the if operator.
unless tests an expression. If it evaluates false,
the rest of the expressions that follow are evaluated,
except for any expressions in a list beginning with the
else symbol. These expressions will be evaluated
if the expression evaluates true.
Looping Operators
while tests an expression. If it evaluates true, the rest of the expressions that follow are evaluated. Then the expression is tested again and evaluations continue until the expression evaluates to false. The following while expression prints the numbers from 1 to 10:
(set i 1) (while (<= i 10) (puts i) (set i (+ i 1)))
until can be seen as the opposite of the while operator. until tests an expression. If it evaluates false, the rest of the expressions that follow are evaluated. Then the expression is tested again and evaluations continue until the expression evaluates to true. The following until expression prints the numbers from 1 to 10:
(set i 1) (until (eq i 10) (puts i) (set i (+ i 1)))
for acts like the C for loop. Its first argument should be a list of three expressions that will be evaluated (1) to initialize the loop, (2) to test whether to evaluate the loop body, and (3) to modify a state variable after each time the loop body is evaluated. The rest of the expressions are used as the loop body. The following for expression prints the numbers from 1 to 10:
(for ((set i 1) (<= i 10) (set i (+ i 1))) (puts i))
break throws an exception that will be caught by the innermost while, until, or for loop, which will immediately terminate.
continue throws an exception that will be caught by the innermost while, until, or for loop, which will immediately continue to the next loop iteration.
Sequencing Operators
progn evaluates a sequence of expression and returns the result of the last evaluation. Many Nu operators contain implicit progn operators.
send sends a message to an object. Normally it is not needed, but for a few kinds of objects, such as blocks, functions, and macros, the normal list syntax for message sending is treated as a call. This operator was added to allow messages to be sent to these objects.
Functions
function creates a named function in the current evaluation context. It expects three arguments: the function name, a list of function parameters, and the body of the function. The body of the function is an implicit progn.
(function addtwo (x y) (+ x y))
do is used to create blocks, otherwise known as anonymous functions. As an example, the following expression creates a block that returns the sum of its two arguments:
(do (x y) (+ x y))
A block is represented by a list of argument names, an execution context
(saved when the block is created), and the parsed code to be evaluated.
The do operator can be used to explicitly create blocks; several other
operators create blocks implicitly.
Blocks and functions can now be defined to accept variable numbers of arguments. To do this, the last parameter in the parameter list should begin with an asterisk; this name (including the asterisk) will be bound to a list of remaining arguments when the block is evaluated. That list can be nil if no additional arguments are specified.
% (function my-apply (operator *operands) (eval (cons operator *operands))) % (my-apply + 1 2 3) 6
An implicit variable named *args is available in the body of a block or function. *args contains a list of all arguments that are passed into the block or function.
% (function f (a b) (puts "Arg1 = #{a}, all args = #{*args}")) % (f 1 2) Arg1 = 1, all args = (1 2)
It's a good idea to not use function or block argument parameters named *args so that there is no conflict with the implicit variable. However, if a parameter named *args appears in a block or function's argument list, it will override the implicit variable.
When a block is created with the function operator or called anonymously, all of its arguments are evaluated in the calling context before the block is evaluated. Most of the time, the evaluation of code in a block takes place in the context that was saved when the block was created.
Macros
Note: the functionality of macro has changed in Nu 0.4.0. Macro definitions now require argument lists just like functions and blocks, and there is no longer an implicit quote applied to the body of the macro. The old style macro operator is still available, but has been renamed macro-0.
Macros are similar to functions, although they provide two additional features that are not available when defining a function or block:
- Macros execute in the evaluation context of the calling block.
- The body of a macro can control how its arguments are evaluated.
macro creates a named macro in the current evaluation context. It expects three arguments: the macro name, the argument list, and the body of the macro. The body of a macro consists of one or more expressions.
A macro is executed in two phases. The first phase is macro-expansion. During macro-expansion, the body of the macro is evaluated using the values passed into the macro via its argument list. Any symbols in the calling context that have the same name as the macro arguments are temporarily masked until the expansion is complete.
Once the macro-expansion phase is complete, the execution phase takes place, where the macro-expanded code is executed in the caller's context.
Here's a simple example of a macro that increments a variable in-place:
(macro inc! (n) `(set ,n (+ ,n 1)))
During the macro-expansion phase, Nu generates code using the calling context and the argument list variables. Calling the inc! macro with an argument of a expands to this:
;; the macro-expansion phase for the call (inc! a): (set a (+ a 1))
Normally, macro-expansion is followed immediately by execution so the above intermediate macro-expansion code is not seen:
% (set a 1) 1 % (inc! a) 2 % a 2
Gensyms
There are often times when local variables are needed in the body of a macro. Since a macro is executed in the context of the caller, there is a chance that the name of a local variable in the macro definition might conflict with a name of a variable that is already defined in the calling context.
An example of how macro variables can conflict with the calling context:
(macro badmacro (x y) `(progn ;; a and b hold temp values (set a (* ,x ,x)) (set b (* ,y ,y)) (+ a b)))
The above macro computes the sum of the squares of x and y (a macro isn't needed for this, but it illustrates an important point). If a variable named a or b is already defined in the calling context, the body of badmacro will overwrite the calling context's values:
% ;; nush is the calling context % (set a 3) 3 % (set b 2) 2 % (badmacro a b) 13 % a 9 % b 4
Unusual variable names could be employed in the body of the macro to reduce the chances of a conflict in variable names:
(macro not-as-bad-macro (x y) ;; but still a danger `(progn ;; unusual-name-a and unusual-name-b hold temp values (set unusual-name-a (* ,x ,x)) (set unusual-name-b (* ,y ,y)) (+ unusual-name-a unusual-name b)))
This is clearly safer, but there is still no way to guarantee that the caller is not using the same unusual variable names.
There is a solution: Nu can generate variable names that are guaranteed to be unique at runtime. These generated variables are known as gensyms (a name that originated with Lisp and is short for generated symbol).
The way to declare a gensym variable in a Nu macro is to begin the variable name with a double underscore. When the macro is expanded, all gensym variables are replaced with unique variable names.
(macro goodmacro (x y) `(progn ;; __a and __b will be replaced with unique names (set __a (* ,x ,x)) (set __b (* ,y ,y)) (+ __a __b)))
The above macro has two gensym variables. At macro-expansion time, the gensyms will be replaced by variables that are guaranteed to be unique and there will no longer be a chance of conflicting with variables in the calling context.
For the curious, the macro-expansion for the above call to goodmacro looks like this:
(progn (set g1025202362__a (* a a)) (set g1025202362__b (* b b)) (+ g1025202362__a g1025202362__b))
Destructuring Argument Lists
Nu macros also support destructuring argument lists. Destructuring takes the place of writing extra parsing code to manually pick apart a nested argument list inside the body of a macro.
For example, here is a way to implement a simple for-loop operator with macro. The var, start and stop arguments are grouped into a sublist within the macro parameter list:
% (macro myfor ((var start stop) *body) `(let ((,var ,start) (__gstop ,stop)) ;; only evaluate 'stop' once (while (<= ,var __gstop) ,@*body (set ,var (+ ,var 1)))))
The above macro looks more natural from the caller's perspective as well:
% (set n 0) 0 % ;; Sum up the first 10 natural integers % (myfor (i 1 10) (set n (+ n i))) % n 55
The above for-loop macro also demonstrates another common idiom when writing macros: using a final argument name that starts with an asterisk to capture the remaining unmatched arguments passed to the macro call. In many macros, including the example above, the "remaining unmatched arguments" will be a body of code.
The ,@ operator (shorthand for quasiquote-splice) conveniently "splices" the body of code into the body of the macro.
macro can destructure arbitrarily complex argument lists:
% (macro add-diagonal (((x1 x2 x3) (y1 y2 y3) (z1 z2 z3))) `(+ ,x1 ,y2 ,z3)) % (add-diagonal ((1 2 3) (4 5 6) (7 8 9))) 15
The Implicit *args Variable
As in functions and blocks, there is an implicit variable named args available in the body of a macro definition. args contains the entire list of arguments passed into the macro.
It's a good idea to not declare a macro argument parameter named *args so that there is no conflict with the implicit variable. However, if a parameter named *args appears in a macro's argument list, it will override the implicit variable.
Here's a simple example of using *args to print out all of the arguments passed into a macro:
% (macro mymacro (operator *operands) `(progn (puts "Arg list: #{*args}") ;; do something useful )) % (mymacro + 1 2 3) Arg list: (+ 1 2 3)
Macro Expansion
When writing or debugging a macro, it is sometimes helpful to see what code the macro-expansion phase is generating without actually evaluating the macro form. macrox does exactly this.
% (macrox (myfor (i 1 10) (set n (+ n i)))) (let ((i 1) (g1350490027__gstop 10)) (while (\<= i g1350490027__gstop) (set n (+ n i)) (set i (+ i 1))))
The macro-expanded code that is returned by macrox can generally be evaluated directly by eval, which should have the same effect as just calling the macro directly.
More about macros
A short tutorial on writing Nu macros can be found here.
Classes and Methods
The class operator defines or extends a class. If a subclass is specified, presumably a new class is to be created. Subsequent expressions within the operator may be used to add instance methods, class methods, and instance variables to the class.
When the class operator is used to create a new class, the class's parent class must be specified after the is keyword.
(class MyWindowController is NSWindowController ... )
When the class operator is used to extend a class that has already been defined, you can omit the superclass.
(class NSString ... )
imethod adds an instance method to a class. It should only be used within a class operator. Return type and argument types may be specified in the method declaration. The is keyword marks the end of the interface definition and the beginning of the method body.
The following example adds a method to a subclass of NSView:
(class NuRocksView is NSView ... (imethod (void) drawRect:(NSRect) rect is ... ))
Type names must be specified in parentheses. The types that can be specified are listed in the following table:
void | No value. Use this to specify that a method returns no value. (void) should never be used as the type of an argument. |
id | An object. The Nu equivalent is an instance of any class. |
int | An integer. The Nu equivalent is an NSNumber. |
BOOL | A boolean. The Nu equivalent is an NSNumber. |
double | A double. The Nu equivalent is an NSNumber. |
float | A float. The Nu equivalent is an NSNumber. |
NSRect | A rectangle. The Nu equivalent is a list of four numbers. |
NSPoint | A point. The Nu equivalent is a list of two numbers. |
NSSize | A size. The Nu equivalent is a list of two numbers. |
NSRange | A range. The Nu equivalent is a list of two numbers. |
SEL | A selector. The Nu equivalent is a string that corresponds to the selector name. |
Class | A class instance. Classes may be specified with a symbol that matches the class name. |
See the sample programs for many examples. If type information is omitted, the Objective-C runtime will be checked for a method with a matching selector. If found, its method signature will be used. If there is no matching selector, the return type and all argument types will be assumed to be (id).
As a convenience, a dash (-) is a synonym for imethod. So if you prefer, you can create instance methods with this simplified syntax:
(class NuRocksView is NSView ... (- drawRect:rect is ... ))
This creates an instance method named drawRect. The new method uses the signature that is obtained by sending instanceMethodSignatureForSelector: to the class being extended. For more examples of the brief syntax, see the "NuRocks":/nurocks sample program.
When a block is added as a method, it is wrapped in a libffi closure that automatically adds self and super to the block's context each time it is evaluated. Method arguments are always evaluated in the calling context before the method block is evaluated.
cmethod adds a class method to a class. It should only be used within a class operator. Its usage mirrors that of imethod. As a convenience, a plus sign (+) is a synonym for cmethod.
ivar adds typed instance variables to a class. It should only be used before any instances of the associated class have been created. Any number of new instance variables can be specified in a single ivar operator. Each new instance variable is specified by its return type and name. Here is an example from the "Benwanu":/benwanu sample program:
(ivar (id) view (id) progressBar (id) imageRep (int) offset (double) minX (double) minY (double) maxX (double) maxY (int) width (int) height)
ivars adds dynamic instance variables to a class. This operator should only be used before any instances of the associated class have been created. It adds a hidden ivar to the class that's used to point to an NSMutableDictionary. From then on, you can add ivars to class instances whenever you want. Whenever you set an ivar, If there's no corresponding one in the runtime, its value will be added to the dictionary with its name as the key.
ivar-accessors adds automatic get and set methods for all instance variables of a class. These methods are implemented using the handleUnknownMessage:withContext: method of NSObject(Nu).
Exception Handling Operators
try wraps a sequence of statement evaluations in an exception handler. Expressions that follow are evaluated until a list beginning with catch is reached. The expressions in this list are not evaluated unless an exception is thrown by the evaluated expressions, in which case, execution jumps to the code in the catch section.
(try (do-something-dangerous) (catch (exception) (handle-exception exception))
throw throws an exception. Any object may be thrown as the exception.
% (try - (throw 22) - (catch (object) - (puts object))) 22
Thread Control Operators
synchronized evaluates a list of expressions after synchronizing on an object. The synchronization object is the first argument.
(synchronized object (task1) (task2) ...)
System Operators
load loads a file or bundle. To load a file from a specific bundle, use the following form:
(load "bundlename:filename")
system executes an operating system command.
(system "mkdir foo")
puts writes a string to the console followed by a carriage return. print writes a string to the console with no carriage return. Both operators return nil.
% (puts "hello") hello () % (progn - (print "hello, ") - (puts "world")) hello, world ()
help returns help text for an object.
% (help do) This operator is used to create blocks. For example, the following expression creates a block that returns the sum of its two arguments: (do (x y) (+ x y))
version returns a string describing the current version of Nu.
beep causes the system to beep.