Node:Top, Next:, Previous:(dir), Up:(dir)


Node:Copying, Next:, Previous:Top, Up:Top

Copying

librep is distributed under the terms of the GNU General Public License, this basically means that you can give it to anyone for any price as long as full source code is included; you also have the right to distribute modified copies in the same way. For the actual legalese see the file COPYING in the distribution (or see (emacs)Copying).

In case it isn't obvious, scripts written to use librep are not considered derived works, and therefore may be licensed however the author wishes. However, the ability of scripts to dynamically load external libraries may complicate this situation.

The distribution includes the following code from other packages:

Be aware that there is absolutely NO WARRANTY for this program, you use it at your own risk. Obviously I hope there are no bugs, but I make no promises regarding the reliability of this software.


Node:Introduction, Next:, Previous:Copying, Up:Top

Introduction

librep is a dialect of Lisp, designed to be used both as an extension language for applications, and for use as a general programming language. It was originally written to be mostly-compatible with Emacs Lisp, but has subsequently diverged markedly. Its aim is to combine the best features of Scheme and Common Lisp and provide an environment that is comfortable for implementing both small and large scale systems. It tries to be a "pragmatic" programming language.

The author has used librep in its various forms in many projects since 1993. This includes two large programs which use it as an extension language, and many stand-alone programs.

rep stands for "Read, Eval, Print", the three main components of any Lisp system.

Some of the features of librep are:


Node:News, Next:, Previous:Introduction, Up:Top

News

0.13

0.12.4

0.12.3

0.12.2

0.12.1

0.12

0.11.3

0.11.2

0.11.1

0.11

0.10

0.9

0.8.1

Fixed some documentation bugs; fixed some build problems

0.8

0.7.1

0.7

0.6.2

0.6.1

No new features; minor portability tweaks and build changes. Fix bug of trying to load directories as Lisp scripts

0.6

0.5

0.4

0.3

0.2

0.1

First public release.


Node:Invocation, Next:, Previous:News, Up:Top

Invocation

The rep program may be used to launch the stand-alone librep environment:

usage: rep [rep-options...] [script [script-options...]]

Where rep-options may be any of the following:

--init file
Use file to boot the Lisp system from, instead of init.jl.
--version
Print the current version number and exit
--batch
Tell the interpreter that it is running non-interactively, this reduces the number of messages output to the console
--interp
Interpreted mode. Never load compiled Lisp files: this can be useful when using the debugger.
--no-rc
Don't load the user's ~/.reprc script, or the site-init.jl script
-f function
Invoke the Lisp function function (with no arguments)
-l script
Try to load the Lisp file script, this is equivalent to evaluating the form (load "script").
-q
Terminate the Lisp process and exit.

If script is given, it names the Lisp file to load, equivalent to the -l option, except that --batch-mode is implied. Any script-options will be made available to the script (in the command-line-args variable).

After any arguments have been processed a banner message will be displayed before entering an interactive read-eval-print loop, unless --batch-mode was specified, in which case the interpreter exits.

The read-eval-print loop simply reads complete Lisp forms (see The Lisp Reader), evaluates them, before printing the result back to the console; this continues ad infinitum, or until you force an EOF (i.e. enter C-d).

Implicitly Interpreting rep Scripts

The rep interpreter also supports automatic invocation of scripts, using the oeprating system's support for #! interpreter invocation (i.e. if the first line of an executable text file contains #! prog, the program prog is used to execute the script.

However there is a problem with this method, in that the PATH environment variable is not searched for the location of the interpreter, and thus the full file name of the interpreter program must be hard-coded into the script. To work around this problem rep supports a slightly different method of invocation.

If the first two characters of a loaded Lisp file are #!, then everything is treated as a comment until the first occurrence of the string !#. This allows the first part of the script to be executed as a shell script invoking the rep interpreter.

What this means, is that you want to put something like the following at the start of any scripts you want to execute implicitly (and chmod +x the file as well):

#!/bin/sh
exec rep "$0" "$@"
!#

;; Lisp code follows...


Node:The language, Next:, Previous:Invocation, Up:Top

The language

This chapter of the manual is a full guide to the librep Lisp programming language, including documentation for most of the built-in functions.

This manual still fails to document the following functions: default-boundp, default-value, recursive-edit, regexp-cache-control, sdbm-close, sdbm-delete, sdbm-error, sdbm-fetch, sdbm-firstkey, sdbm-nextkey, sdbm-open, sdbm-rdonly, sdbm-store, sdbmp, set-default, setq-default,


Node:Intro, Next:, Up:The language

Introduction

As you have probably gathered by now, librep provides a dialect of the Lisp programming language--a dialect originally inspired by Emacs Lisp, but later adapted to include many features from various Scheme implementations and Common Lisp. The language dialect aims to be convenient for both extending applications and writing large stand-alone programs.

All programs written using only the information in this manual should be compatible with future revisions of librep.

This following sections explain some of the most important Lisp concepts and the conventions I've used in this manual.


Node:nil and t, Next:, Up:Intro

nil and t

In the rep Lisp dialect there is a single data value representing boolean "false"--the empty list, written as (). All other values are considered "not-false", i.e. "true".

By convention the constants nil and t are used to represent the canonical boolean values. The constant variable nil evaluates to the empty list (i.e. "false"), while t evaluates to itself (i.e. not-"false", therefore "true").

Reiterating, all of the conditional operations regard anything which is not () as being true (i.e. non-false). The actual symbol t should be used where a true boolean value is explicitly stated, to increase the clarity of the code.

So, (), and its alias nil, represent both the empty list and boolean falsehood. Most Lisp programmers write () where its value as a list should be emphasized, and nil where its value as boolean false is intended. Although neither of these values need be quoted (see Quoting), most programmers will quote the empty list to emphasize that it is a constant value. However nil should not be quoted, doing so would produce the symbol nil, not boolean falsehood. For example:

(append '() '()) => ()          ;Emphasize use of empty lists

(not nil) => t                  ;Emphasize use as boolean false

(get 'nil 'color)               ;Use the symbol nil

When a function is said to "return false", it means that it returns the false boolean value, i.e. the empty list. When a function is said to "return true", this means that any non-false value is returned.


Node:The Lisp Reader, Next:, Previous:nil and t, Up:Intro

The Lisp Reader

Lisp programs and functions are stored internally as Lisp data objects, the Lisp Reader is the mechanism that translates from textual descriptions of Lisp objects to the internal data structures representing them.

The Lisp Reader is the collection of internal functions accessed by the read Lisp function. It reads a character at a time from an input stream until a whole Lisp object has been parsed.

See Data Types.


Node:Notation, Next:, Previous:The Lisp Reader, Up:Intro

Notation

Wherever an example of evaluating a Lisp form is shown it will be formatted like this,

(+ 1 2)
    => 3

The glyph => is used to show the computed value of a form. 1

When two forms are shown as being exactly equivalent to one another the glyph == is used, for example,

(car some-variable) == (nth 0 some-variable)

Evaluating some forms result in an error being signalled, this is denoted by the error--> glyph.

(open-file "/tmp/foo" 'read)
    error--> File error: No such file or directory, /tmp/foo


Node:Descriptions, Previous:Notation, Up:Intro

Descriptions

In this document the simplest type of descriptions are those defining variables (see Variables), they look something like:

grains-of-sand Variable
This imaginary variable contains the number of grains of sand in a one-mile long stretch of an averagely sandy beach.

Hooks (see Hooks) are also described in this format, the only difference is that Variable: is replaced by Hook:.

Functions (see Functions) and macros (see Macros) have more complex descriptions; as well as the name of the object being described, they also have a list of parameters which the object will accept. Each parameter in the list is named and may be referred to in the body of the description.

Three keyword parameters may also be used: #!optional, #!key and #!rest. They have the same meaning as when used in the lambda-list of a function definition (see Lambda Expressions). That is, #!optional means that all further parameters are optional, and #!rest means that the following parameter actually receives a list of any unused argument values.

An example function definition follows.

useless-function first #!optional second #!rest tail Function
This function returns a list consisting of the values second (when undefined the number 42 is used), all the items in the list tail and first.
(useless-function 'foo 'bar 'xyz 20)
    => (bar xyz 20 foo)

(useless-function '50)
    => (42 50)

Macros and interactive commands are defined in the same way with Macro: or Command: replacing Function:.

Special forms (see Special Forms) are described similarly to functions except that the argument list is formatted differently, since special forms are, by definition, more flexible in how they treat their arguments. Optional values are enclosed in square brackets ([optional-arg]) and three dots (repeated-arg...) indicate where zero or more arguments are allowed.


Node:Data Types, Next:, Previous:Intro, Up:The language

Data Types

The way that data is represented in Lisp is fundamentally different to languages such as C or Fortran. In Lisp each piece of data (or value) has two basic attributes: the data and the type of the data. This means that type checking is performed at run-time on the actual data itself, not at compile-time on the "variable" holding the data.

Also, there are no "pointers" in Lisp. As in the Java programming language, all values are references to data structures, with each actual data structure (or Lisp Object) being able to have as many values referring to it concurrently as necessary. Because of this lack of pointers, there can be no memory-leakage in Lisp--when an object has no more extant references, it is automatically deallocated (see Garbage Collection).

Most Lisp objects are a member of one of the primitive types; these are types built into the Lisp system and can represent things like strings, numbers, cons cells, vectors, etc... Other primitive types may be defined at run-time.

More complex objects may be constructed from these primitive types, for example a vector of three elements could be regarded as a type triple if necessary. In general, each separate type provides a predicate function which returns true when applied to an object of its own type.

Finally, one of the most important differences between Lisp and other languages is that there is no distinction between programs and data. But this will be explained later.


Node:Types Summary, Next:, Up:Data Types

Types Summary

Each separate data type is documented in its own section, this is a just a summary of the more common types.

Numbers
Numbers: fixnums, bignums, rationals and floats. See Numbers.
Cons cell
An object referring to two other Lisp objects. See Cons Cells.
List
A sequence of objects, in Lisp lists are not primitive types, instead they are made by chaining together Cons cells. See Lists.
Vector
A one-dimensional array of objects. See Vectors.
String
A vector of characters. See Strings.
Array
An ordered sequence of objects which can be accessed in constant time, either a vector or a string. See Sequences.
Sequence
An ordered sequence of objects, either a list or an array. See Sequences.
Symbol
A symbol is a named object; they are used to provide named variables and functions. See Symbols.
File
A link to a notional file in the filing system. This file may be in the local filing system, or on a FTP server, or wherever. See Files.
Process
An object through which processes may be created and controlled. See Processes.
Stream
Serial data sinks and sources. These may include files, functions, and processes. See Streams.
Void
The empty type, only used in symbols to represent an undefined value. Note that this is not the same as (), which is the empty list, or false truth value.


Node:Read Syntax, Next:, Previous:Types Summary, Up:Data Types

Read Syntax

As previously noted the Lisp reader translates textual descriptions of Lisp objects into the object they describe (source files are simply descriptions of objects). However, not all data types can be created in this way: in fact the only types which can are numbers, strings, symbols, cons cells (or lists) and vectors, all others have to be created by calling functions.

Single line comments are introduced by a semi-colon character (;). Whenever the Lisp reader encounters a semi-colon where it's looking for the read syntax of a new Lisp object it will discard the rest of the line of input. Block comments are also supported, introduced by the string #| and terminated by |#. See Comment Styles.

The read syntax of an object is the string which when given to the reader as input will produce the object. The read syntax of each type of object is documented in that type's main section of this manual but here is a small summary of how to write each type.

Numbers
A number is number written as an integer--decimal, octal (when the number is preceded by #o) or hexadecimal (when the number is preceded by #x)--or a decimal rational or floating point value. An optional minus sign may be the first character in a number. Some examples are,
42
    => 42

#o177
    => 127

#x-ff
    => -255

3/2
    => 3/2

1.23
    => 1.23

Strings
The read syntax of a string is simply the string with a double-quote character (") at each end, for more details see Strings.
"This is a string"

Cons cells
A cons cell is written in what is known as dotted pair notation, an opening left-parenthesis, followed by the read syntax of the first object, followed by a dot, then the second object, and finally a closing right-parenthesis. For example:
("car" . "cdr")

Lists
The syntax of a list is similar to a cons cell, but the dot is removed and zero or more objects may be written:
(0 1 2 3)

("foo" ("bar" "baz") 100)

The second example is a list of three elements, a string, an inner list and a number.

Vectors
The read syntax of a vector is similar to that of a list, but with square brackets instead of parentheses,
[0 1 2 3]

Symbols
The read syntax of a symbol is its name, for example the read syntax of the symbol called my-symbol is,
my-symbol


Node:Printed Representation, Next:, Previous:Read Syntax, Up:Data Types

Printed Representation

As well as translating textual descriptions to Lisp objects, the process may be reversed, converting a value back to a textual description. The resulting text is known as the printed representation of the object, and will usually be very similar to the read syntax of the object (see Read Syntax).

Objects which do not have a read syntax do have a printed representation, it will normally be of the form,

#<relevant-text>

where the relevant-text is object-dependent and usually describes the object and its contents. The reader will signal an error if it encounters a description of an object in the format #<...>.


Node:Equality Predicates, Next:, Previous:Printed Representation, Up:Data Types

Equality Predicates

eq arg1 arg2 Function
Returns true when arg1 and arg2 refer to the same object. Two objects are the same when they occupy the same place in memory and hence modifying one object would alter the other. The following Lisp fragments may illustrate this,
(eq "foo" "foo")	;the objects are distinct
    => ()

(eq t t)		;the same object -- the symbol t
    => t

Note that the result of eq is undefined when called on two integer objects with the same value, see eql.

equal arg1 arg2 Function
The function equal compares the structure of the two objects arg1 and arg2. If they are considered to be equivalent then returns true, otherwise returns false.
(equal "foo" "foo")
    => t

(equal 42 42)
    => t

(equal 42 0)
    => ()

(equal '(x . y) '(x . y))
    => t

eql arg1 arg2 Function
This function is a cross between eq and equal: if arg1 and arg2 are both numbers then the value of these numbers are compared. Otherwise it behaves in exactly the same manner as eq does.
(eql 3 3)
    => t

(eql 1 2)
    => ()

(eql "foo" "foo")
    => ()

(eql 'x 'x)
    => t


Node:Comparison Predicates, Next:, Previous:Equality Predicates, Up:Data Types

Comparison Predicates

These functions compare their two arguments in a scalar fashion, the arguments may be of any type but the results are only meaningful for numbers, strings (ASCII values of each byte compared until a non-matching pair is found then those two values are compared as numbers) and cons cells (cars compared before cdrs).

Unlike the eql function, inexact and exact numbers will be compared by first coercing the exact number to be inexact.

= arg1 arg2 arg3 ... argn Function
Returns true if all arguments represent the same value.

/= arg1 arg2 arg3 ... argn Function
Returns true if no two arguments represent the same value.

> arg1 arg2 arg3 ... argn Function
Returns true when arg1 is `greater than' arg2, and arg2 is greater than arg3, and so on, upto argn.

>= arg1 arg2 arg3 ... argn Function
Similar to >, but for the "greater than or equal to" relation.

< arg1 arg2 arg3 ... argn Function
Similar to >, but for the "less than" relation.

<= arg1 arg2 arg3 ... argn Function
Similar to >, but for the "less than or equal to" relation.

There are two related functions for finding the maximum or minimum of a sequence of values.

max #!rest args Function
Return the maximum value from the list of args. When comparing numbers, any inexact arguments cause the result to be inexact.

min #!rest args Function
Return the minimum value from the list of args. When comparing numbers, any inexact arguments cause the result to be inexact.


Node:Type Predicates, Next:, Previous:Comparison Predicates, Up:Data Types

Type Predicates

Each type has a corresponding predicate which defines the objects which are members of that type. Each predicate function has a single parameter, if that parameter is of the correct type it returns true.

integerp, numberp, null, consp, listp, vectorp, subrp, functionp, sequencep, stringp, symbolp, processp, filep.

The documentation for these functions is with the documentation for the relevant type.


Node:Garbage Collection, Previous:Type Predicates, Up:Data Types

Garbage Collection

In Lisp, data objects are used very freely; a side effect of this is that it is not possible to (easily) know when an object is stale, that is, no references to it exist and it can therefore be reused.

The garbage collector is used to overcome this problem; whenever enough memory has been allocated to make it worthwhile, evaluation stops and the garbage collector works its way through memory deciding which objects may still be referenced, and which are stale. The stale objects are then recorded as being available for reuse and evaluation continues. (But see Guardians)

garbage-collect Function
Runs the garbage collector, usually this function doesn't need to be called manually.

garbage-threshold Variable
The number of bytes of data that must have been allocated since the last garbage collection before evaluation pauses and the garbage collector is invoked. Its default value is about 100K.

idle-garbage-threshold Variable
When the input loop is idle (due to a lack of input), this is the number of bytes of data that must have been allocated since the garbage collection, for another collection to be triggered.

This is usually set to a lot less than garbage-threshold since the small delay caused by garbage collection is unnoticeable if the system is already idle.

after-gc-hook Variable
A hook (see Normal Hooks) called immediately after each invocation of the garbage collector.


Node:Numbers, Next:, Previous:Data Types, Up:The language

Numbers

Librep distinguishes between numbers that are represented exactly and numbers that may not be. This is similar to the Scheme dialect of Lisp. Quoting from the Scheme standard:

... numbers are either exact or inexact. A number is exact if it was written as an exact constant or was derived from exact numbers using only exact operations. A number is inexact if it was written as an inexact constant, if it was derived using inexact ingredients, or if it was derived using inexact operations. Thus inexactness is a contagious property of a number.

Exact numbers include both integers and rational numbers, there is no theoretical limit to the range of the values that may be represented 2. Inexact numbers are currently implemented using double precision floating point values.

The read syntax of any number is: [pfx...][sgn]data..., where the optional sgn is one of the characters - or +, data is the representation of the number, and pfx is zero or more of the following prefix strings:

#b
#B
Integers are described in binary,
#o
#O
Integers are in octal,
#d
#D
Integers are in decimal (the default),
#x
#X
Integers are in hexadecimal,
#e
#E
Coerce the number to an exact representation after parsing it,
#i
#I
Coerce to an inexact representation.

The representation of an integer is simply the digits representing that integer, in the radix chosen by any given prefix (defaults to decimal). Examples of valid integer read syntaxes for the number 42 could be 42, #x2a, #o52, #o+52, ...

The representation of a rational number is two sequences of digits, separated by a / character. For example, 3/2 represents the rational number three divided by two.

Inexact numbers are parsed from one of two representations: decimal point form, which is simply a decimal number containing a decimal point, and exponential form, which is a decimal number followed by the letter e and a decimal exponent multiplying the first part of the number by that power of ten. For example, 10.0, 10. and 1e1 all read as the inexact number ten. Note that the radix prefixes currently have no effect when parsing inexact numbers, decimal is used exclusively.

An integer's printed representation is simply the number printed in decimal with a preceding minus sign if it is negative. Rational numbers are printed as two integers separated by a / character. Inexact numbers are printed in their decimal form.

numberp object Function
Returns true if object is a number.


Node:Arithmetic Functions, Next:, Up:Numbers

Arithmetic Functions

There are a number of functions which perform arithmetic operations on numbers, they take a varying number of values as their arguments returning a new number as their result. When given only exact arguments, an exact result will be returned.

+ number1 #!rest numbers Function
This functions adds its arguments then returns their sum.

- number1 #!rest numbers Function
If this function is just given one argument (number1) that number is negated and returned. Otherwise each of numbers is subtracted from a running total starting with the value of number1.
(- 20)
    => -20

(- 20 10 5)
    => 5

* number1 #!rest numbers Function
This function multiplies its arguments then returns the result.

/ number1 #!rest numbers Function
This function performs division, a running-total (initialised from number1 is successively divided by each of numbers then the result is returned.
(/ 100 2)
    => 50

(/ 200 2 5)
    => 20

(/ 3 2)
    => 3/2

(/ 3.0 2)
    => 1.5

1+ number Function
This function returns the result of adding one to number.
(1+ 42)
    => 43

1- number Function
Returns number minus one.


Node:Integer Functions, Next:, Previous:Arithmetic Functions, Up:Numbers

Integer Functions

The functions described in this section all operate on, and return, integer values.

quotient dividend divisor Function
Return the integer part of dividing dividend by divisor.

remainder dividend divisor Function
Returns the integer remainder from dividing the dividend by divisor. The remainder is either zero or has the same sign as dividend.

modulo dividend divisor Function
mod dividend divisor Function
Return the value of dividend modulo divisor. Unlike the remainder function the modulo function always has the sign of the divisor, not of the dividend

gcd args... Function
Returns the greatest common divisor of the integers args... If no arguments are given, returns zero.

lcm args... Function
Return the lowest common multiple of the integers args... If no arguments are given, returns one.


Node:Rational Functions, Next:, Previous:Integer Functions, Up:Numbers

Rational Functions

These functions operate on rational numbers.

numerator x Function
Returns the exact numerator of x.

denominator x Function
Returns the exact denominator of x.

exact->inexact x Function
Returns an inexact version of rational number x.


Node:Real Number Functions, Next:, Previous:Rational Functions, Up:Numbers

Real Number Functions

abs x Function
Returns the magnitude of x.

floor x Function
Round x downwards to the nearest integer less than or equal to x.

ceiling x Function
Round x upwards to the nearest integer less than or equal to x.

truncate x Function
Round x to the nearest integer between x and zero.

round x Function
Round x to the nearest integer. Halfway cases are rounded to the nearest even integer.

inexact->exact x Function
Returns an exact representation of x. This may involve a loss of accuracy.


Node:Mathematical Functions, Next:, Previous:Real Number Functions, Up:Numbers

Mathematical Functions

exp x Function
Return `e' (the base of natural logarithms) raised to the power x.

log x Function
Return the natural logarithm of x. An arithmetic error is signalled if x is less than zero.

sin x Function
Return the sine of angle x; x is in terms of radians.

cos x Function
Return the cosine of angle x.

tan x Function
Return the tangent of angle x.

asin x Function
Return the arc sine of x (the value whose sine is x), in radians.

acos x Function
Return the arc cosine of x.

atan x Function
Return the arc tangent of x.

sqrt x Function
Return the non-negative square root of x. Currently, if x is negative, an arithmetic error is signalled.

expt x y Function
Returns x raised to the power y.

If x is negative and y is a non-integer, then an arithmetic error is signalled (mathematically should return a complex number).


Node:Bitwise Functions, Next:, Previous:Mathematical Functions, Up:Numbers

Bitwise Functions

These functions operate on the bit string which an integer represents, assuming a two's complement representation.

lsh number count Function
This function shifts the integer number count bits to the left, if count is negative number is shifted to the right instead.
(lsh 1 8)
    => 256

(lsh 256 -8)
    => 1

logand number1 #!rest numbers Function
This function uses a bit-wise logical `and' operation to combine all its arguments (there must be at least one argument).
(logand 15 8)
    => 8

(logand 15 7 20)
    => 4

logior number1 #!rest numbers Function
Uses a bit-wise logical `inclusive-or' to combine all its arguments (there must always be at least one argument).
(logior 1 2 4)
    => 7

logxor number1 #!rest numbers Function
Uses a bitwise logical `exclusive-or' to combine all its arguments (there must be at least one).
(logxor 7 3)
    => 4

lognot number Function
This function inverts all the bits in number.
(lognot 0)
    => -1

(lognot 2)
    => -3

(lognot -1)
    => 0


Node:Numeric Predicates, Next:, Previous:Bitwise Functions, Up:Numbers

Numeric Predicates

For the documentation of the functions =, /=, >, <, >=, <=, max and min, see Comparison Predicates.

exactp object Function
Returns true when object is an exact number.

inexactp object Function
Returns true when object is an inexact number.

integerp object Function
Returns true when object is an integer.

rationalp object Function
Returns true when object is a rational number (including integers).

realp object Function
Returns true when object is a real number.

oddp x Function
Return true if x is an odd number.

evenp x Function
Return true if x is an even number.

positivep x Function
Return true if x is a number greater than zero.

negativep x Function
Return true if x is a number less than zero.

zerop x Function
Returns true if x is equal to zero.


Node:Random Numbers, Next:, Previous:Numeric Predicates, Up:Numbers

Pseudo-Random Numbers

The random function allows pseudo-random numbers to be generated.

random #!optional limit Function
Return a pseudo-random number between zero and limit-1 inclusive. If limit is undefined, it is taken as being the largest positive integer representable in a fixnum.

Calling random with limit equal to the symbol t seeds the generator with the current time of day.


Node:Characters, Previous:Random Numbers, Up:Numbers

Characters

In librep characters are stored in integers. Their read syntax is a question mark followed by the character itself, which may be an escape sequence introduced by a backslash. For details of the available escape sequences see Strings.

?a
    => 97

?\n
    => 10

?\177
    => 127

alpha-char-p character Function
This function returns true when character is one of the alphabetic characters.
(alpha-char-p ?a)
    => t

upper-case-p character Function
When character is one of the upper-case characters this function returns true.

lower-case-p character Function
Returns true when character is lower-case.

digit-char-p character Function
This function returns true when character is one of the decimal digit characters.

alphanumericp character Function
This function returns true when character is either an alphabetic character or a decimal digit character.

space-char-p character Function
Returns true when character is a white-space character (space, tab, newline or form feed).

char-upcase character Function
This function returns the upper-case equivalent of character. If character is already upper-case or has no upper-case equivalent it is returned unchanged.
(char-upcase ?a)
    => 65                       ;`A'

(char-upcase ?A)
    => 65                       ;`A'

(char-upcase ?!)
    => 33                       ;`!'

char-downcase character Function
Returns the lower-case equivalent of the character character.


Node:Sequences, Next:, Previous:Numbers, Up:The language

Sequences

Sequences are ordered groups of objects, there are several primitive types which can be considered sequences, each with their pros and cons.

A sequence is either an array or a list, where an array is either a vector or a string.

sequencep object Function
This function returns true if object is a sequence.


Node:Cons Cells, Next:, Up:Sequences

Cons Cells

A cons cell is an ordered pair of two objects, the car and the cdr.

The read syntax of a cons cell is an opening parenthesis followed by the read syntax of the car, a dot, the read syntax of the cdr and a closing parenthesis. For example a cons cell with a car of 10 and a cdr of the string foo would be written as,

(10 . "foo")

cons car cdr Function
This function creates a new cons cell. It will have a car of car and a cdr of cdr.
(cons 10 "foo")
    => (10 . "foo")

consp object Function
This function returns true if object is a cons cell.
(consp '(1 . 2))
    => t

(consp '())
    => ()

(consp (cons 1 2))
    => t

The strange syntax '(1 . 2) is known as quoting (see Quoting), it tells the evaluator that the object following the quote-mark is a constant, and therefore should not be evaluated. This will be explained in more detail later.

In Lisp an atom is any object which is not a cons cell (and is, therefore, atomic).

atom object Function
Returns true if object is an atom (not a cons cell).

Given a cons cell there are a number of operations which can be performed on it.

car cons-cell Function
This function returns the object which is the car (first element) of the cons cell cons-cell.
(car (cons 1 2))
    => 1

(car '(1 . 2))
    => 1

cdr cons-cell Function
This function returns the cdr (second element) of the cons cell cons-cell.
(cdr (cons 1 2))
    => 2

(cdr '(1 . 2))
    => 2

rplaca cons-cell new-car Function
This function sets the value of the car (first element) in the cons cell cons-cell to new-car. The value returned is cons-cell.
(setq x (cons 1 2))
    => (1 . 2)
(rplaca x 3)
    => (3 . 2)
x
    => (3 . 2)

rplacd cons-cell new-cdr Function
This function is similar to rplacd except that the cdr slot (second element) of cons-cell is modified.


Node:Lists, Next:, Previous:Cons Cells, Up:Sequences

Lists

A list is a sequence of zero or more objects, the main difference between lists and vectors is that lists are more dynamic: they can change size, be split, reversed, concatenated, etc... very easily.

In Lisp lists are not a primitive type; instead singly-linked lists are formed by chaining cons cells together (see Cons Cells). The empty list is represented by the special value ().

listp arg Function
This functions returns true when its argument, arg, is a list (i.e. either a cons cell or ()).

null arg Function
Returns a true value if arg is the empty list.


Node:List Structure, Next:, Up:Lists

List Structure

Each element in a list is given its own cons cell and stored in the car of that cell. The list is then constructed by having the cdr of a cell point to the cons cell containing the next element (and hence the entire rest of the list). The cdr of the cell containing the last element in the list is (). A list of zero elements is represented by ().

The read syntax of a list is an opening parenthesis, followed by the read syntax of zero or more space-separated objects, followed by a closing parenthesis. Alternatively, lists can be constructed `manually' using dotted-pair notation.

All of the following examples result in the same list of five elements: the numbers from zero to four.

(0 1 2 3 4)

(0 . (1 . (2 . (3 . (4 . ())))))

(0 1 2 . (3 4))

An easy way to visualise lists and how they are constructed is to see each cons cell in the list as a separate box with pointers to its car and cdr,

+-----+-----+
|  o  |  o----> cdr
+--|--+-----+
   |
    --> car

Complex box-diagrams can now be drawn to represent lists. For example the following diagram represents the list (1 2 3 4).

+-----+-----+   +-----+-----+   +-----+-----+   +-----+-----+
|  o  |  o----> |  o  |  o----> |  o  |  o----> |  o  |  o----> ()
+--|--+-----+   +--|--+-----+   +--|--+-----+   +--|--+-----+
   |               |               |               |
    --> 1           --> 2           --> 3           --> 4

A more complex example, the list ((1 2) (foo bar)) can be drawn as,

+-----+-----+                          +-----+-----+
|  o  |  o---------------------------> |  o  |  o----> ()
+--|--+-----+                          +--|--+-----+
   |                                      |
+-----+-----+   +-----+-----+          +-----+-----+   +-----+-----+
|  o  |  o----> |  o  |  o----> ()     |  o  |  o----> |  o  |  o----> ()
+--|--+-----+   +--|--+-----+          +--|--+-----+   +--|--+-----+
   |               |                      |               |
    --> 1           --> 2                  --> foo         --> bar


Node:Building Lists, Next:, Previous:List Structure, Up:Lists

Building Lists

It has already been described how you can create lists using the Lisp reader; this method does have a drawback though: the list created is effectively static. If you modify the contents of the list and that list was created when a function was defined the list will remain modified for all future invocations of that function. This is not usually a good idea, consider the following function definition,

(defun bogus-function (x)
  "Return a list whose first element is nil and whose second element is X."
  (let
      ((result '(nil nil)))     ;Static list which is filled in each time
    (rplaca (cdr result) x)     ; the function is called
    result))

This function does in fact do what its documentation claims, but a problem arises when it is called more than once,

(setq x (bogus-function 'foo))
    => (nil foo)
(setq y (bogus-function 'bar))
    => (nil bar)               ;The first result has been destroyed
x
    => (nil bar)               ;See!

This example is totally contrived--no one would ever write a function like the one in the example but it does demonstrate the need for a dynamic method of creating lists.

list #!rest elements Function
This function creates a list out of its arguments, if zero arguments are given the empty list, (), is returned.
(list 1 2 3)
    => (1 2 3)

(list (major-version-number) (minor-version-number))
    => (3 2)

(list)
    => ()

list* arg1 arg2 ... argn-1 argn Function
Creates a new list (arg1 arg2 ... argn-1 . argn).
(list* 1 2 '(3 4))
    => (1 2 3 4)

make-list length #!optional initial-value Function
This function creates a list length elements long. If the initial-value argument is given it defines the value of all elements in the list, if it is not defined they are all ().
(make-list 2)
    => (() ())

(make-list 3 t)
    => (t t t)

(make-list 0)
    => ()

append #!rest lists Function
This function creates a new list with the elements of each of its arguments (which must be lists). Unlike the function nconc this function preserves the structure of all its arguments.
(append '(1 2 3) '(4 5))
    => (1 2 3 4 5)

(append)
    => ()

What actually happens is that all arguments but the last are copied, then the last argument is linked on to the end of the list (uncopied).

(setq foo '(1 2))
    => (1 2)
(setq bar '(3 4))
    => (3 4)
(setq baz (append foo bar))
    => (1 2 3 4)
(eq (nthcdr 2 baz) bar)
    => t

The following diagram shows the final state of the three variables more clearly,

foo--> +-----+-----+   +-----+-----+
       |  o  |  o----> |  o  |     |
       +--|--+-----+   +--|--+-----+
          |               |
          o--> 1          o--> 2   bar
          |               |          ->
baz--> +--|--+-----+   +--|--+-----+   +-----+-----+   +-----+-----+
       |  o  |  o----> |  o  |  o----> |  o  |  o----> |  o  |     |
       +-----+-----+   +-----+-----+   +--|--+-----+   +--|--+-----+
                                          |               |
                                           --> 3           --> 4

Note how foo and the first half of baz use the same objects for their elements--copying a list only copies its cons cells, its elements are reused. Also note how the variable bar actually references the mid-point of baz since the last list in an append call is not copied.

remove elt list Function
Return a copy of list, with all elements the same as elt discarded (using the equal function to compare).

remq elt list Function
Similar to the remove function, except that comparisons are made using eq.

reverse list Function
This function returns a new list; it is made from the elements of the list list in reverse order. Note that this function does not alter its argument.
(reverse '(1 2 3 4))
    => (4 3 2 1)

As a postscript to this section, the function used as an example at the beginning could now be written as,

(defun not-so-bogus-function (x)
  (list nil x))

Also note that the cons function can be used to create lists by hand and to add new elements onto the front of a list. For example:

(setq x (list 1 2 3))
    => (1 2 3)
(setq x (cons 0 x))
    => (0 1 2 3)


Node:Accessing List Elements, Next:, Previous:Building Lists, Up:Lists

Accessing List Elements

The most flexible method of accessing an element in a list is via a combination of the car and cdr functions. There are other functions which provide an easier way to get at the elements in a flat list. These will usually be faster than a string of car and cdr operations.

nth count list Function
This function returns the element count elements down the list, therefore to access the first element use a count of zero (or even better the car function). If there are too few elements in the list and no element number count can be found () is returned.
(nth 3 '(0 1 2 3 4 5))
    => 3

(nth 0 '(foo bar)
    => foo

nthcdr count list Function
This function takes the cdr of the list list count times, returning the last cdr taken.
(nthcdr 3 '(0 1 2 3 4 5))
    => (3 4 5)

(nthcdr 0 '(foo bar))
    => (foo bar)

last list Function
This function returns the last element in the list list. If the list has zero elements () is returned.
(last '(1 2 3))
    => 3

(last '())
    => ()

member object list Function
This function scans through the list list until it finds an element which is equal to object. The tail of the list (the cons cell whose car is the matched object) is then returned. If no elements match object then the empty list () is returned.
(member 'c '(a b c d e))
    => (c d e)

(member 20 '(1 2))
    => ()

memq object list Function
This function is similar to member except that comparisons are performed by the eq function not equal.


Node:Modifying Lists, Next:, Previous:Accessing List Elements, Up:Lists

Modifying Lists

The nthcdr function can be used in conjunction with the rplaca function to modify an arbitrary element in a list. For example,

(rplaca (nthcdr 2 '(0 1 2 3 4 5)) 'foo)
    => foo

sets the third element of the list (0 1 2 3 4 5) to the symbol called foo.

There are also functions which modify the structure of a whole list. These are called destructive operations because they modify the actual structure of a list--no copy is made. This can lead to unpleasant side effects if care is not taken.

nconc #!rest lists Function
This function is the destructive equivalent of the function append, it modifies its arguments so that it can return a list which is the concatenation of the elements in its arguments lists.

Like all the destructive functions this means that the lists given as arguments are modified (specifically, the cdr of their last cons cell is made to point to the next list). This can be seen with the following example (similar to the example in the append documentation).

(setq foo '(1 2))
    => (1 2)
(setq bar '(3 4))
    => (3 4)
(setq baz (nconc foo bar))
    => (1 2 3 4)
foo
    => (1 2 3 4)                ;`foo' has been altered!
(eq (nthcdr 2 baz) bar)
    => t

The following diagram shows the final state of the three variables more clearly,

foo-->                           bar-->
baz--> +-----+-----+   +-----+-----+   +-----+-----+   +-----+-----+
       |  o  |  o----> |  o  |  o----> |  o  |  o----> |  o  |     |
       +--|--+-----+   +--|--+-----+   +--|--+-----+   +--|--+-----+
          |               |               |               |
           --> 1           --> 2             --> 3           --> 4

nreverse list Function
This function rearranges the cons cells constituting the list list so that the elements are in the reverse order to what they were.
(setq foo '(1 2 3))
    => (1 2 3)
(nreverse foo)
    => (3 2 1)
foo
    => (1)                      ;`foo' wasn't updated when the list
                                ; was altered.

delete object list Function
This function destructively removes all elements of the list list which are equal to object then returns the modified list.
(delete 1 '(0 1 0 1 0))
    => (0 0 0)

When this function is used to remove an element from a list which is stored in a variable that variable must be set to the return value of the delete function. Otherwise, if the first element of the list has to be deleted (because it is equal to object) the value of the variable will not change.

(setq foo '(1 2 3))
    => (1 2 3)
(delete 1 foo)
    => (2 3)
foo
    => (1 2 3)
(setq foo (delete 1 foo))
    => (2 3)

delq object list Function
This function is similar to the delete function, the only difference is that the eq function is used to compare object with each of the elements in list, instead of the equal function which is used by delete.

sort list #!optional predicate Function
Destructively sorts (i.e. by modifying cdrs) the list of values list, to satisfy the function predicate, returning the sorted list. If predicate is undefined, the < function is used, sorting the list into ascending order.

predicate is called with two values, it should return true if the first is considered less than the second.

(sort '(5 3 7 4))
    => (3 4 5 7)

The sort is stable, in that elements in the list which are equal will preserve their original positions in relation to each other.


Node:Association Lists, Next:, Previous:Modifying Lists, Up:Lists

Association Lists

An association list (or alist) is a list mapping keys to to. Each element of the alist is a cons cell, the car of which is the key, the cdr the value that it associates to. For example an alist could look like,

((fred . 20)
 (bill . 30))

this alist has two keys, fred and bill which both associate to an integer (20 and 30 respectively).

It is possible to make the associated values lists, this looks like,

((fred 20 male)
 (bill 30 male)
 (sue  25 female))

in this alist the symbol fred is associated with the list (20 male).

There are a number of functions which let you interrogate an alist with a given key for its association.

assoc key alist Function
This function scans the association list alist for the first element whose car is equal to key, this element is then returned. If no match of key is found false is returned.
(assoc 'two '((one . 1) (two . 2) (three . 3)))
    => (two . 2)

assq key alist Function
Similar to the function assoc except that the function eq is used to compare elements instead of equal.

It is not usually wise to use assq when the keys of the alist may not be symbols--eq won't think two objects are equivalent unless they are the same object!

(assq "foo" '(("bar" . 1) ("foo" . 2)))
    => ()
(assoc "foo" '(("bar" . 1) ("foo" . 2)))
    => ("foo" . 2)

rassoc association alist Function
This function searches through alist until it finds an element whose cdr is equal to association, that element is then returned. false will be returned if no elements match.
(rassoc 2 '((one . 1) (two . 2) (three . 3)))
    => (two . 2)

rassq association alist Function
This function is equivalent to rassoc except that it uses eq to make comparisons.


Node:Infinite Lists, Previous:Association Lists, Up:Lists

Infinite Lists

Sometimes it is useful to be able to create `infinite' lists--that is, lists which appear to have no last element--this can easily be done in Lisp by linking the cdr of the last cons cell in the list structure back to the beginning of the list.

 -----------------------------------
|                                   |
 --> +-----+-----+   +-----+-----+  |
     |  o  |  o----> |  o  |  o-----
     +--|--+-----+   +--|--+-----+
        |               |
         --> 1           --> 2

The diagram above represents the infinite list (1 2 1 2 1 2 ...).

Infinite lists have a major drawback though, many of the standard list manipulation functions can not be used on them. These functions work by moving through the list until they reach the end. If the list has no end the function may never terminate and the only option is to send the interpreter an interrupt signal.

The only functions which may be used on circular lists are: the cons cell primitives (cons, car, cdr, rplaca, rplacd), nth and nthcdr.

Also note that infinite lists can't be printed. But note the print-length and print-level variables, see Output Functions.


Node:Vectors, Next:, Previous:Lists, Up:Sequences

Vectors

A vector is a fixed-size sequence of Lisp objects, each element may be accessed in constant time--unlike lists where the time taken to access an element is proportional to the position of the element.

The read syntax of a vector is an opening square bracket, followed by zero or more space-separated objects, followed by a closing square bracket. For example,

[zero one two three]

In general it is best to use vectors when the number of elements to be stored is known and lists when the sequence may grow or shrink.

vectorp object Function
This function returns true if its argument, object, is a vector.

vector #!rest elements Function
This function creates a new vector containing the arguments given to the function.
(vector 1 2 3)
    => [1 2 3]

(vector)
    => []

make-vector size #!optional initial-value Function
Returns a new vector, size elements big. If initial-value is defined each element of the new vector is set to initial-value, otherwise they are all ().
(make-vector 4)
    => [() () () ()]

(make-vector 2 t)
    => [t t]


Node:Strings, Next:, Previous:Vectors, Up:Sequences

Strings

A string is a vector of characters (see Characters), they are generally used for storing and manipulating pieces of text. librep puts no restrictions on the values which may be stored in a string--specifically, the null character (^@) may be stored with no problems.

The read syntax of a string is a double quote character, followed by the contents of the string, the object is terminated by a second double quote character. For example, "abc" is the read syntax of the string abc.

Any backslash characters in the string's read syntax introduce an escape sequence; one or more of the following characters are treated specially to produce the next actual character in the string.

The following escape sequences are supported (all are shown without their leading backslash \ character).

n
A newline character.
r
A carriage return character.
f
A form feed character.
t
A TAB character.
a
A `bell' character (this is Ctrl-g).
\
A backslash character.
^c
The `control' code of the character c. This is calculated by toggling the seventh bit of the upper-case version of c.

For example,

\^C             ;A Ctrl-c character (ASCII value 3)
\^@            ;The NUL character (ASCII value 0)

012
The character whose ASCII value is the octal value 012. After the backslash character the Lisp reader reads up to three octal digits and combines them into one character.
x12
The character whose ASCII value is the hexadecimal value 12, i.e. an x character followed by one or two hex digits.

stringp object Function
This function returns true if its argument is a string.

make-string length #!optional initial-character Function
Creates a new string containing length characters, each character is initialised to initial-character (or to spaces if initial-character is not defined).
(make-string 3)
    => "   "

(make-string 2 ?$)
    => "$$"

concat #!rest args Function
This function concatenates all of its arguments, args, into a single string which is returned. If no arguments are given then the null string () results.

Each of the args may be a string, a character or a list or vector of characters. Characters are stored in strings modulo 256.

(concat "foo" "bar")
    => "foobar"

(concat "a" ?b)
    => "ab"

(concat "foo" [?b ?a ?r])
    => "foobar"

(concat)
    => ""

substring string start #!optional end Function
This function creates a new string which is a partial copy of the string string. The first character copied is start characters from the beginning of the string. If the end argument is defined it is the index of the character to stop copying at, if it is not defined all characters until the end of the string are copied.
(substring "xxyfoozwx" 3 6)
    => "foo"

(substring "xyzfoobar" 3)
    => "foobar"

string= string1 string2 Function
This function compares the two strings string1 and string2--if they are made from the same characters in the same order then true is returned.
(string= "one" "one")
    => t

(string= "one" "two")
    => ()

Note that an alternate way to compare strings (or anything!) is to use the equal function.

string-equal string1 string2 Function
Returns true if string1 and string2 are the same, ignoring differences in character case.

string< string1 string2 Function
This function returns true if string1 is `less' than string2. This is determined by comparing the two strings a character at a time, the first pair of characters which do not match each other are then compared with a normal `less-than' function.

In librep the standard < function understands strings so string< is just a macro calling that function.

(string< "abc" "abd")
    => t

(string< "abc" "abb")
    => ()

string-lessp string1 string2 Function
Similar to string< but ignores character case in comparisons.

See String Functions for a few more string manipulating functions, and Regular Expressions for a method of pattern matching in strings.


Node:Array Functions, Next:, Previous:Strings, Up:Sequences

Array Functions

arrayp object Function
This function returns true if object is an array.

aref array position Function
Returns the element of the array (vector or string) array position elements from the first element (i.e. the first element is numbered zero). If no element exists at position in array, false is returned.
(aref [0 1 2 3] 2)
    => 2

(aref "abcdef" 3)
    => 100                      ;`d'

aset array position value Function
This function sets the element of the array array with an index of position (counting from zero) to value. An error is signalled if element position does not exist. The result of the function is value.
(setq x [0 1 2 3])
    => [0 1 2 3]
(aset x 2 'foo)
    => foo
x
    => [0 1 foo 3]


Node:Sequence Functions, Previous:Array Functions, Up:Sequences

Sequence Functions

sequencep arg Function
Returns true if arg is a sequence, i.e. a list or an array.

length sequence Function
This function returns the length (an integer) of the sequence sequence.
(length "abc")
    => 3

(length '(1 2 3 4))
    => 4

(length [x y])
    => 2

copy-sequence sequence Function
Returns a new copy of the sequence sequence. Where possible (in lists and vectors) only the `structure' of the sequence is newly allocated: the same objects are used for the elements in both sequences.
(copy-sequence "xy")
    => "xy"

(setq x '("one" "two"))
    => ("one" "two")
(setq y (copy-sequence x))
    => ("one" "two")
(eq x y)
    => ()
(eq (car x) (car y))
    => t

elt sequence position Function
This function returns the element of sequence position elements from the beginning of the sequence.

This function is a combination of the nth and aref functions.

(elt [0 1 2 3] 1)
    => 1

(elt '(foo bar) 0)
    => foo


Node:Symbols, Next:, Previous:Sequences, Up:The language

Symbols

Symbols are objects with a name (almost always a unique name). They are one of the most important data types in Lisp since they are used to provided named variables (see Variables) and functions (see Functions).

symbolp arg Function
This function returns true when its argument is a symbol.


Node:Symbol Syntax, Next:, Up:Symbols

Symbol Syntax

The read syntax of a symbol is usually its name; however, if the name contains any meta-characters (whitespace or any from ()[]'";|\) they will have to be entered specially. There are two ways to tell the reader that a meta-character is actually part of the symbol's name:

  1. Precede the meta-character by a backslash character (\), for example:
    xy\(z\)                 ;the symbol whose name is xy(z)
    
  2. Enclose part of the name in vertical bars (two | characters). All characters after the starting vertical line are copied as-is until the closing vertical line is encountered. For example:
    xy|(z)|                 ;the symbol xy(z)
    

Here are some example read syntaxes.

setq                    ; setq
|setq|                  ; setq
\s\e\t\q                ; setq
1                       ; the number 1
\1                      ; the symbol 1
|!$%zf78&|              ; !$%zf78&
foo|(bar)|              ; foo(bar)
foo\(bar\)              ; foo(bar)


Node:Symbol Attributes, Next:, Previous:Symbol Syntax, Up:Symbols

Symbol Attributes

All symbols have two basic attributes: print name and property list. Most important is the print name of the symbol. This is a string naming the symbol, after it has been defined (when the symbol is first created) it may not be changed.

symbol-name symbol Function
This function returns the print name of the symbol symbol.
(symbol-name 'unwind-protect)
    => "unwind-protect"

The symbol's property list (or plist) is similar to an alist (see Association Lists), though stored differently, and provides a method of storing arbitrary extra values in each symbol. See Property Lists.

Although not strictly an attribute of the symbol, symbols also provide a means of associating values with names (i.e. variables). Within a defined context, a symbol may have a binding, this binding associates the symbol with a memory location within which a value may be stored. When writing Lisp programs, the value of a symbol's current binding is accessed by writing the print name of the symbol. Similarly the binding may be modifi