Next: , Previous: , Up: The language   [Contents][Index]

5.11 Block-Structured Definitions

Previous sections of this document have described several special forms and macros for defining top-level functions and variables. Librep also provides a higher-level method of creating these definitions, the define statement. It allows block-structured programs to be defined intuitively.

The define originates in Scheme.

The most basic use of define is very similar to defun, e.g. the two following forms have exactly the same effect:

(defun foo (x) (1+ x))

(define (foo x) (1+ x))

But note the different position of the parentheses. This is because define may also be used to define (lexical) variables. (see Defining Variables) Hence the following is also equivalent:

(define foo (lambda (x) (1+ x)))

However this is the most uninteresting aspect of define. More interesting is that it allows internal definitions.

Within a define form, any inner calls to define (that occur in a contiguous block at the start of the body of a let, let*, letrec, lambda, or define form) are also used to create definitions, but definitions that are local to the containing scope. For example:

(define (foo x)
  (define (bar)
    (* x 42))
  (1+ (bar)))

This defines a top-level function called foo. However it also contains an inner function named bar, that is only accessible within foo. Since bar is defined inside foo, and librep uses lexical scope by default, the variable x defined by foo may also be accessed by bar.

Macro: define name form
Macro: define (name . args) body-forms…

Define a global lexical variable called name, whose value will be set to form.

If the first argument to the macro is a list, then a function is defined whose name is name and whose formal parameters are specified by args. The body of the function is defined by the body-forms. The body forms have any macros expanded, and are scanned for internal definitions (at the start of the body of let, let*, lambda special forms)

Macro: define-macro name form
Macro: define-macro (name . args) body-forms…

Similar to define, except that it creates a macro definition (see Macros).

Macro: with-internal-definitions body-forms

Recursively expand macros in body-forms, while scanning out any internal definitions into letrec statements.

Next: , Previous: , Up: The language   [Contents][Index]