Reinstate `scm_protects', for backward compatibility.
[bpt/guile.git] / doc / ref / api-procedures.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
f916cbc4 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
7@page
8@node Procedures and Macros
9@section Procedures and Macros
10
11@menu
12* Lambda:: Basic procedure creation using lambda.
13* Primitive Procedures:: Procedures defined in C.
00ce5125 14* Compiled Procedures:: Scheme procedures can be compiled.
07d83abe 15* Optional Arguments:: Handling keyword, optional and rest arguments.
f916cbc4 16* Case-lambda:: One function, multiple arities.
07d83abe
MV
17* Procedure Properties:: Procedure properties and meta-information.
18* Procedures with Setters:: Procedures with setters.
19* Macros:: Lisp style macro definitions.
20* Syntax Rules:: Support for R5RS @code{syntax-rules}.
21* Syntax Case:: Support for the @code{syntax-case} system.
22* Internal Macros:: Guile's internal representation.
23@end menu
24
25
26@node Lambda
27@subsection Lambda: Basic Procedure Creation
28@cindex lambda
29
07d83abe
MV
30A @code{lambda} expression evaluates to a procedure. The environment
31which is in effect when a @code{lambda} expression is evaluated is
32enclosed in the newly created procedure, this is referred to as a
33@dfn{closure} (@pxref{About Closure}).
34
35When a procedure created by @code{lambda} is called with some actual
36arguments, the environment enclosed in the procedure is extended by
37binding the variables named in the formal argument list to new locations
38and storing the actual arguments into these locations. Then the body of
2e4ef7ed 39the @code{lambda} expression is evaluated sequentially. The result of
07d83abe
MV
40the last expression in the procedure body is then the result of the
41procedure invocation.
42
43The following examples will show how procedures can be created using
44@code{lambda}, and what you can do with these procedures.
45
46@lisp
47(lambda (x) (+ x x)) @result{} @r{a procedure}
48((lambda (x) (+ x x)) 4) @result{} 8
49@end lisp
50
51The fact that the environment in effect when creating a procedure is
52enclosed in the procedure is shown with this example:
53
54@lisp
55(define add4
56 (let ((x 4))
57 (lambda (y) (+ x y))))
58(add4 6) @result{} 10
59@end lisp
60
61
62@deffn syntax lambda formals body
63@var{formals} should be a formal argument list as described in the
64following table.
65
66@table @code
67@item (@var{variable1} @dots{})
68The procedure takes a fixed number of arguments; when the procedure is
69called, the arguments will be stored into the newly created location for
70the formal variables.
71@item @var{variable}
72The procedure takes any number of arguments; when the procedure is
73called, the sequence of actual arguments will converted into a list and
74stored into the newly created location for the formal variable.
75@item (@var{variable1} @dots{} @var{variablen} . @var{variablen+1})
76If a space-delimited period precedes the last variable, then the
77procedure takes @var{n} or more variables where @var{n} is the number
78of formal arguments before the period. There must be at least one
79argument before the period. The first @var{n} actual arguments will be
80stored into the newly allocated locations for the first @var{n} formal
81arguments and the sequence of the remaining actual arguments is
82converted into a list and the stored into the location for the last
83formal argument. If there are exactly @var{n} actual arguments, the
84empty list is stored into the location of the last formal argument.
85@end table
86
87The list in @var{variable} or @var{variablen+1} is always newly
88created and the procedure can modify it if desired. This is the case
89even when the procedure is invoked via @code{apply}, the required part
90of the list argument there will be copied (@pxref{Fly Evaluation,,
91Procedures for On the Fly Evaluation}).
92
93@var{body} is a sequence of Scheme expressions which are evaluated in
94order when the procedure is invoked.
95@end deffn
96
97@node Primitive Procedures
98@subsection Primitive Procedures
99@cindex primitives
100@cindex primitive procedures
101
102Procedures written in C can be registered for use from Scheme,
103provided they take only arguments of type @code{SCM} and return
104@code{SCM} values. @code{scm_c_define_gsubr} is likely to be the most
105useful mechanism, combining the process of registration
106(@code{scm_c_make_gsubr}) and definition (@code{scm_define}).
107
108@deftypefun SCM scm_c_make_gsubr (const char *name, int req, int opt, int rst, fcn)
109Register a C procedure @var{FCN} as a ``subr'' --- a primitive
110subroutine that can be called from Scheme. It will be associated with
111the given @var{name} but no environment binding will be created. The
112arguments @var{req}, @var{opt} and @var{rst} specify the number of
113required, optional and ``rest'' arguments respectively. The total
114number of these arguments should match the actual number of arguments
115to @var{fcn}. The number of rest arguments should be 0 or 1.
116@code{scm_c_make_gsubr} returns a value of type @code{SCM} which is a
117``handle'' for the procedure.
118@end deftypefun
119
120@deftypefun SCM scm_c_define_gsubr (const char *name, int req, int opt, int rst, fcn)
121Register a C procedure @var{FCN}, as for @code{scm_c_make_gsubr}
122above, and additionally create a top-level Scheme binding for the
123procedure in the ``current environment'' using @code{scm_define}.
124@code{scm_c_define_gsubr} returns a handle for the procedure in the
125same way as @code{scm_c_make_gsubr}, which is usually not further
126required.
127@end deftypefun
128
129@code{scm_c_make_gsubr} and @code{scm_c_define_gsubr} automatically
130use @code{scm_c_make_subr} and also @code{scm_makcclo} if necessary.
131It is advisable to use the gsubr variants since they provide a
132slightly higher-level abstraction of the Guile implementation.
133
00ce5125
AW
134@node Compiled Procedures
135@subsection Compiled Procedures
136
f916cbc4
AW
137In Guile, procedures can be executed by directly interpreting their
138source code. Scheme source code is a set of nested lists, after all,
139with each list representing a procedure call.
140
141Most procedures are compiled, however. This means that Guile has done
142some pre-computation on the procedure, to determine what it will need
143to do each time the procedure runs. Compiled procedures run faster
144than interpreted procedures.
00ce5125 145
f916cbc4
AW
146Loading files is the normal way that compiled procedures come to
147being. If Guile sees that a file is uncompiled, or that its compiled
148file is out of date, it will attempt to compile the file when it is
149loaded, and save the result to disk. Procedures can be compiled at
150runtime as well. @xref{Read/Load/Eval/Compile}, for more information
151on runtime compilation.
00ce5125 152
5a069042
AW
153Compiled procedures, also known as @dfn{programs}, respond all
154procedures that operate on procedures. In addition, there are a few
46d666d4 155more accessors for low-level details on programs.
5a069042 156
46d666d4
AW
157Most people won't need to use the routines described in this section,
158but it's good to have them documented. You'll have to include the
159appropriate module first, though:
5a069042
AW
160
161@example
162(use-modules (system vm program))
163@end example
164
46d666d4
AW
165@deffn {Scheme Procedure} program? obj
166@deffnx {C Function} scm_program_p (obj)
167Returns @code{#t} iff @var{obj} is a compiled procedure.
168@end deffn
169
81fd3152
AW
170@deffn {Scheme Procedure} program-objcode program
171@deffnx {C Function} scm_program_objcode (program)
73643339
AW
172Returns the object code associated with this program. @xref{Bytecode
173and Objcode}, for more information.
46d666d4
AW
174@end deffn
175
176@deffn {Scheme Procedure} program-objects program
177@deffnx {C Function} scm_program_objects (program)
178Returns the ``object table'' associated with this program, as a
179vector. @xref{VM Programs}, for more information.
5a069042
AW
180@end deffn
181
46d666d4
AW
182@deffn {Scheme Procedure} program-module program
183@deffnx {C Function} scm_program_module (program)
81fd3152
AW
184Returns the module that was current when this program was created. Can
185return @code{#f} if the compiler could determine that this information
186was unnecessary.
46d666d4
AW
187@end deffn
188
f916cbc4
AW
189@deffn {Scheme Procedure} program-free-variables program
190@deffnx {C Function} scm_program_free_variables (program)
191Returns the set of free variables that this program captures in its
192closure, as a vector. If a closure is code with data, you can get the
193code from @code{program-objcode}, and the data via
194@code{program-free-variables}.
195
196Some of the values captured are actually in variable ``boxes''.
197@xref{Variables and the VM}, for more information.
46d666d4
AW
198
199Users must not modify the returned value unless they think they're
200really clever.
201@end deffn
202
46d666d4 203@deffn {Scheme Procedure} program-meta program
f916cbc4 204@deffnx {C Function} scm_program_meta (program)
46d666d4
AW
205Return the metadata thunk of @var{program}, or @code{#f} if it has no
206metadata.
207
208When called, a metadata thunk returns a list of the following form:
f916cbc4 209@code{(@var{bindings} @var{sources} @var{arities} . @var{properties})}. The format
46d666d4
AW
210of each of these elements is discussed below.
211@end deffn
212
5a069042 213@deffn {Scheme Procedure} program-bindings program
f916cbc4 214@deffnx {Scheme Procedure} make-binding name boxed? index start end
5a069042 215@deffnx {Scheme Procedure} binding:name binding
f916cbc4 216@deffnx {Scheme Procedure} binding:boxed? binding
5a069042
AW
217@deffnx {Scheme Procedure} binding:index binding
218@deffnx {Scheme Procedure} binding:start binding
219@deffnx {Scheme Procedure} binding:end binding
220Bindings annotations for programs, along with their accessors.
221
222Bindings declare names and liveness extents for block-local variables.
223The best way to see what these are is to play around with them at a
f916cbc4 224REPL. @xref{VM Concepts}, for more information.
5a069042 225
81fd3152
AW
226Note that bindings information is stored in a program as part of its
227metadata thunk, so including it in the generated object code does not
228impose a runtime performance penalty.
5a069042
AW
229@end deffn
230
231@deffn {Scheme Procedure} program-sources program
232@deffnx {Scheme Procedure} source:addr source
233@deffnx {Scheme Procedure} source:line source
234@deffnx {Scheme Procedure} source:column source
235@deffnx {Scheme Procedure} source:file source
236Source location annotations for programs, along with their accessors.
237
46d666d4
AW
238Source location information propagates through the compiler and ends
239up being serialized to the program's metadata. This information is
240keyed by the offset of the instruction pointer within the object code
241of the program. Specifically, it is keyed on the @code{ip} @emph{just
242following} an instruction, so that backtraces can find the source
243location of a call that is in progress.
5a069042
AW
244@end deffn
245
f916cbc4
AW
246@deffn {Scheme Procedure} program-arities program
247@deffnx {C Function} scm_program_arities (program)
248@deffnx {Scheme Procedure} program-arity program ip
249@deffnx {Scheme Procedure} arity:start arity
250@deffnx {Scheme Procedure} arity:end arity
251@deffnx {Scheme Procedure} arity:nreq arity
252@deffnx {Scheme Procedure} arity:nopt arity
253@deffnx {Scheme Procedure} arity:rest? arity
254@deffnx {Scheme Procedure} arity:kw arity
255@deffnx {Scheme Procedure} arity:allow-other-keys? arity
256Accessors for a representation of the ``arity'' of a program.
257
258The normal case is that a procedure has one arity. For example,
259@code{(lambda (x) x)}, takes one required argument, and that's it. One
260could access that number of required arguments via @code{(arity:nreq
261(program-arities (lambda (x) x)))}. Similarly, @code{arity:nopt} gets
262the number of optional arguments, and @code{arity:rest?} returns a true
263value if the procedure has a rest arg.
264
265@code{arity:kw} returns a list of @code{(@var{kw} . @var{idx})} pairs,
266if the procedure has keyword arguments. The @var{idx} refers to the
267@var{idx}th local variable; @xref{Variables and the VM}, for more
268information. Finally @code{arity:allow-other-keys?} returns a true
269value if other keys are allowed. @xref{Optional Arguments}, for more
270information.
271
272So what about @code{arity:start} and @code{arity:end}, then? They
273return the range of bytes in the program's bytecode for which a given
274arity is valid. You see, a procedure can actually have more than one
275arity. The question, ``what is a procedure's arity'' only really makes
276sense at certain points in the program, delimited by these
277@code{arity:start} and @code{arity:end} values.
278@end deffn
279
5a069042 280@deffn {Scheme Procedure} program-properties program
46d666d4
AW
281Return the properties of a @code{program} as an association list,
282keyed by property name (a symbol).
283
284Some interesting properties include:
285@itemize
286@item @code{name}, the name of the procedure
287@item @code{documentation}, the procedure's docstring
288@end itemize
289@end deffn
290
291@deffn {Scheme Procedure} program-property program name
292Access a program's property by name, returning @code{#f} if not found.
293@end deffn
294
295@deffn {Scheme Procedure} program-documentation program
5a069042 296@deffnx {Scheme Procedure} program-name program
46d666d4 297Accessors for specific properties.
5a069042 298@end deffn
00ce5125 299
07d83abe
MV
300@node Optional Arguments
301@subsection Optional Arguments
302
07d83abe
MV
303Scheme procedures, as defined in R5RS, can either handle a fixed number
304of actual arguments, or a fixed number of actual arguments followed by
305arbitrarily many additional arguments. Writing procedures of variable
306arity can be useful, but unfortunately, the syntactic means for handling
307argument lists of varying length is a bit inconvenient. It is possible
f916cbc4 308to give names to the fixed number of arguments, but the remaining
07d83abe
MV
309(optional) arguments can be only referenced as a list of values
310(@pxref{Lambda}).
311
f916cbc4
AW
312For this reason, Guile provides an extension to @code{lambda},
313@code{lambda*}, which allows the user to define procedures with
314optional and keyword arguments. In addition, Guile's virtual machine
315has low-level support for optional and keyword argument dispatch.
316Calls to procedures with optional and keyword arguments can be made
317cheaply, without allocating a rest list.
07d83abe
MV
318
319@menu
f916cbc4
AW
320* lambda* and define*:: Creating advanced argument handling procedures.
321* ice-9 optargs:: (ice-9 optargs) provides some utilities.
07d83abe
MV
322@end menu
323
324
f916cbc4
AW
325@node lambda* and define*
326@subsubsection lambda* and define*.
07d83abe 327
f916cbc4
AW
328@code{lambda*} is like @code{lambda}, except with some extensions to
329allow optional and keyword arguments.
07d83abe 330
edcd3e83
KR
331@deffn {library syntax} lambda* ([var@dots{}] @* [#:optional vardef@dots{}] @* [#:key vardef@dots{} [#:allow-other-keys]] @* [#:rest var | . var]) @* body
332@sp 1
333Create a procedure which takes optional and/or keyword arguments
334specified with @code{#:optional} and @code{#:key}. For example,
07d83abe
MV
335
336@lisp
337(lambda* (a b #:optional c d . e) '())
338@end lisp
339
edcd3e83
KR
340is a procedure with fixed arguments @var{a} and @var{b}, optional
341arguments @var{c} and @var{d}, and rest argument @var{e}. If the
07d83abe
MV
342optional arguments are omitted in a call, the variables for them are
343bound to @code{#f}.
344
f916cbc4
AW
345@fnindex define*
346Likewise, @code{define*} is syntactic sugar for defining procedures
347using @code{lambda*}.
348
349@code{lambda*} can also make procedures with keyword arguments. For
350example, a procedure defined like this:
07d83abe
MV
351
352@lisp
f916cbc4
AW
353(define* (sir-yes-sir #:key action how-high)
354 (list action how-high))
07d83abe
MV
355@end lisp
356
f916cbc4
AW
357can be called as @code{(sir-yes-sir #:action 'jump)},
358@code{(sir-yes-sir #:how-high 13)}, @code{(sir-yes-sir #:action
359'lay-down #:how-high 0)}, or just @code{(sir-yes-sir)}. Whichever
360arguments are given as keywords are bound to values (and those not
361given are @code{#f}).
07d83abe 362
edcd3e83
KR
363Optional and keyword arguments can also have default values to take
364when not present in a call, by giving a two-element list of variable
365name and expression. For example in
07d83abe
MV
366
367@lisp
f916cbc4
AW
368(define* (frob foo #:optional (bar 42) #:key (baz 73))
369 (list foo bar baz))
07d83abe
MV
370@end lisp
371
372@var{foo} is a fixed argument, @var{bar} is an optional argument with
373default value 42, and baz is a keyword argument with default value 73.
edcd3e83
KR
374Default value expressions are not evaluated unless they are needed,
375and until the procedure is called.
07d83abe 376
edcd3e83
KR
377Normally it's an error if a call has keywords other than those
378specified by @code{#:key}, but adding @code{#:allow-other-keys} to the
379definition (after the keyword argument declarations) will ignore
380unknown keywords.
07d83abe 381
edcd3e83
KR
382If a call has a keyword given twice, the last value is used. For
383example,
07d83abe
MV
384
385@lisp
f916cbc4
AW
386(define* (flips #:key (heads 0) (tails 0))
387 (display (list heads tails)))
388
389(flips #:heads 37 #:tails 42 #:heads 99)
edcd3e83 390@print{} (99 42)
07d83abe
MV
391@end lisp
392
edcd3e83
KR
393@code{#:rest} is a synonym for the dotted syntax rest argument. The
394argument lists @code{(a . b)} and @code{(a #:rest b)} are equivalent
395in all respects. This is provided for more similarity to DSSSL,
396MIT-Scheme and Kawa among others, as well as for refugees from other
397Lisp dialects.
398
399When @code{#:key} is used together with a rest argument, the keyword
400parameters in a call all remain in the rest list. This is the same as
401Common Lisp. For example,
07d83abe 402
edcd3e83
KR
403@lisp
404((lambda* (#:key (x 0) #:allow-other-keys #:rest r)
405 (display r))
406 #:x 123 #:y 456)
407@print{} (#:x 123 #:y 456)
408@end lisp
409
410@code{#:optional} and @code{#:key} establish their bindings
f916cbc4
AW
411successively, from left to right. This means default expressions can
412refer back to prior parameters, for example
edcd3e83
KR
413
414@lisp
415(lambda* (start #:optional (end (+ 10 start)))
416 (do ((i start (1+ i)))
417 ((> i end))
418 (display i)))
419@end lisp
f916cbc4
AW
420
421The exception to this left-to-right scoping rule is the rest argument.
422If there is a rest argument, it is bound after the optional arguments,
423but before the keyword arguments.
07d83abe
MV
424@end deffn
425
426
f916cbc4
AW
427@node ice-9 optargs
428@subsubsection (ice-9 optargs)
07d83abe 429
f916cbc4
AW
430Before Guile 2.0, @code{lambda*} and @code{define*} were implemented
431using macros that processed rest list arguments. This was not optimal,
432as calling procedures with optional arguments had to allocate rest
433lists at every procedure invocation. Guile 2.0 improved this
434situation by bringing optional and keyword arguments into Guile's
435core.
07d83abe 436
f916cbc4
AW
437However there are occasions in which you have a list and want to parse
438it for optional or keyword arguments. Guile's @code{(ice-9 optargs)}
439provides some macros to help with that task.
07d83abe 440
f916cbc4
AW
441The syntax @code{let-optional} and @code{let-optional*} are for
442destructuring rest argument lists and giving names to the various list
443elements. @code{let-optional} binds all variables simultaneously, while
444@code{let-optional*} binds them sequentially, consistent with @code{let}
445and @code{let*} (@pxref{Local Bindings}).
446
447@deffn {library syntax} let-optional rest-arg (binding @dots{}) expr @dots{}
448@deffnx {library syntax} let-optional* rest-arg (binding @dots{}) expr @dots{}
449These two macros give you an optional argument interface that is very
450@dfn{Schemey} and introduces no fancy syntax. They are compatible with
451the scsh macros of the same name, but are slightly extended. Each of
452@var{binding} may be of one of the forms @var{var} or @code{(@var{var}
453@var{default-value})}. @var{rest-arg} should be the rest-argument of the
454procedures these are used from. The items in @var{rest-arg} are
455sequentially bound to the variable names are given. When @var{rest-arg}
456runs out, the remaining vars are bound either to the default values or
457@code{#f} if no default value was specified. @var{rest-arg} remains
458bound to whatever may have been left of @var{rest-arg}.
07d83abe 459
f916cbc4
AW
460After binding the variables, the expressions @var{expr} @dots{} are
461evaluated in order.
462@end deffn
07d83abe 463
f916cbc4
AW
464Similarly, @code{let-keywords} and @code{let-keywords*} extract values
465from keyword style argument lists, binding local variables to those
466values or to defaults.
07d83abe 467
f916cbc4
AW
468@deffn {library syntax} let-keywords args allow-other-keys? (binding @dots{}) body @dots{}
469@deffnx {library syntax} let-keywords* args allow-other-keys? (binding @dots{}) body @dots{}
470@var{args} is evaluated and should give a list of the form
471@code{(#:keyword1 value1 #:keyword2 value2 @dots{})}. The
472@var{binding}s are variables and default expressions, with the
473variables to be set (by name) from the keyword values. The @var{body}
474forms are then evaluated and the last is the result. An example will
475make the syntax clearest,
476
477@example
478(define args '(#:xyzzy "hello" #:foo "world"))
07d83abe 479
f916cbc4
AW
480(let-keywords args #t
481 ((foo "default for foo")
482 (bar (string-append "default" "for" "bar")))
483 (display foo)
484 (display ", ")
485 (display bar))
486@print{} world, defaultforbar
487@end example
07d83abe 488
f916cbc4
AW
489The binding for @code{foo} comes from the @code{#:foo} keyword in
490@code{args}. But the binding for @code{bar} is the default in the
491@code{let-keywords}, since there's no @code{#:bar} in the args.
492
493@var{allow-other-keys?} is evaluated and controls whether unknown
494keywords are allowed in the @var{args} list. When true other keys are
495ignored (such as @code{#:xyzzy} in the example), when @code{#f} an
496error is thrown for anything unknown.
497@end deffn
498
499@code{(ice-9 optargs)} also provides some more @code{define*} sugar,
500which is not so useful with modern Guile coding, but still supported:
501@code{define*-public} is the @code{lambda*} version of
502@code{define-public}; @code{defmacro*} and @code{defmacro*-public}
503exist for defining macros with the improved argument list handling
504possibilities. The @code{-public} versions not only define the
505procedures/macros, but also export them from the current module.
506
507@deffn {library syntax} define*-public formals body
508Like a mix of @code{define*} and @code{define-public}.
07d83abe
MV
509@end deffn
510
511@deffn {library syntax} defmacro* name formals body
512@deffnx {library syntax} defmacro*-public name formals body
513These are just like @code{defmacro} and @code{defmacro-public} except that they
514take @code{lambda*}-style extended parameter lists, where @code{#:optional},
515@code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
516semantics. Here is an example of a macro with an optional argument:
517
518@lisp
519(defmacro* transmorgify (a #:optional b)
f916cbc4 520 (a 1))
07d83abe
MV
521@end lisp
522@end deffn
523
f916cbc4
AW
524@node Case-lambda
525@subsection Case-lambda
526@cindex SRFI-16
527@cindex variable arity
528@cindex arity, variable
529
530R5RS's rest arguments are indeed useful and very general, but they
531often aren't the most appropriate or efficient means to get the job
532done. For example, @code{lambda*} is a much better solution to the
533optional argument problem than @code{lambda} with rest arguments.
534
535@fnindex case-lambda
536Likewise, @code{case-lambda} works well for when you want one
537procedure to do double duty (or triple, or ...), without the penalty
538of consing a rest list.
539
540For example:
541
542@lisp
543(define (make-accum n)
544 (case-lambda
545 (() n)
546 ((m) (set! n (+ n m)) n)))
547
548(define a (make-accum 20))
549(a) @result{} 20
550(a 10) @result{} 30
551(a) @result{} 30
552@end lisp
553
554The value returned by a @code{case-lambda} form is a procedure which
555matches the number of actual arguments against the formals in the
556various clauses, in order. The first matching clause is selected, the
557corresponding values from the actual parameter list are bound to the
558variable names in the clauses and the body of the clause is evaluated.
559If no clause matches, an error is signalled.
560
561The syntax of the @code{case-lambda} form is defined in the following
562EBNF grammar. @dfn{Formals} means a formal argument list just like
563with @code{lambda} (@pxref{Lambda}).
564
565@example
566@group
567<case-lambda>
568 --> (case-lambda <case-lambda-clause>)
569<case-lambda-clause>
570 --> (<formals> <definition-or-command>*)
571<formals>
572 --> (<identifier>*)
573 | (<identifier>* . <identifier>)
574 | <identifier>
575@end group
576@end example
577
578Rest lists can be useful with @code{case-lambda}:
579
580@lisp
581(define plus
582 (case-lambda
583 (() 0)
584 ((a) a)
585 ((a b) (+ a b))
586 ((a b . rest) (apply plus (+ a b) rest))))
587(plus 1 2 3) @result{} 6
588@end lisp
589
590@fnindex case-lambda*
591Also, for completeness. Guile defines @code{case-lambda*} as well,
592which is like @code{case-lambda}, except with @code{lambda*} clauses.
593A @code{case-lambda*} clause matches if the arguments fill the
594required arguments, but are not too many for the optional and/or rest
595arguments.
596
f916cbc4
AW
597Keyword arguments are possible with @code{case-lambda*}, but they do
598not contribute to the ``matching'' behavior. That is to say,
599@code{case-lambda*} matches only on required, optional, and rest
600arguments, and on the predicate; keyword arguments may be present but
601do not contribute to the ``success'' of a match. In fact a bad keyword
602argument list may cause an error to be raised.
07d83abe
MV
603
604@node Procedure Properties
605@subsection Procedure Properties and Meta-information
606
f916cbc4
AW
607In addition to the information that is strictly necessary to run,
608procedures may have other associated information. For example, the
609name of a procedure is information not for the procedure, but about
610the procedure. This meta-information can be accessed via the procedure
611properties interface.
07d83abe 612
f916cbc4
AW
613The first group of procedures in this meta-interface are predicates to
614test whether a Scheme object is a procedure, or a special procedure,
615respectively. @code{procedure?} is the most general predicates, it
616returns @code{#t} for any kind of procedure. @code{closure?} does not
617return @code{#t} for primitive procedures, and @code{thunk?} only
618returns @code{#t} for procedures which do not accept any arguments.
07d83abe
MV
619
620@rnindex procedure?
621@deffn {Scheme Procedure} procedure? obj
622@deffnx {C Function} scm_procedure_p (obj)
623Return @code{#t} if @var{obj} is a procedure.
624@end deffn
625
626@deffn {Scheme Procedure} closure? obj
627@deffnx {C Function} scm_closure_p (obj)
f916cbc4
AW
628Return @code{#t} if @var{obj} is a closure. This category somewhat
629misnamed, actually, as it applies only to interpreted procedures, not
630compiled procedures. But since it has historically been used more to
631select on implementation details than on essence (closure or not), we
632keep it here for compatibility. Don't use it in new code, though.
07d83abe
MV
633@end deffn
634
635@deffn {Scheme Procedure} thunk? obj
636@deffnx {C Function} scm_thunk_p (obj)
637Return @code{#t} if @var{obj} is a thunk.
638@end deffn
639
07d83abe 640@cindex procedure properties
f916cbc4
AW
641Procedure properties are general properties associated with
642procedures. These can be the name of a procedure or other relevant
07d83abe
MV
643information, such as debug hints.
644
645@deffn {Scheme Procedure} procedure-name proc
646@deffnx {C Function} scm_procedure_name (proc)
647Return the name of the procedure @var{proc}
648@end deffn
649
650@deffn {Scheme Procedure} procedure-source proc
651@deffnx {C Function} scm_procedure_source (proc)
f916cbc4
AW
652Return the source of the procedure @var{proc}. Returns @code{#f} if
653the source code is not available.
07d83abe
MV
654@end deffn
655
656@deffn {Scheme Procedure} procedure-environment proc
657@deffnx {C Function} scm_procedure_environment (proc)
f916cbc4 658Return the environment of the procedure @var{proc}. Very deprecated.
07d83abe
MV
659@end deffn
660
661@deffn {Scheme Procedure} procedure-properties proc
662@deffnx {C Function} scm_procedure_properties (proc)
f916cbc4
AW
663Return the properties associated with @var{proc}, as an association
664list.
07d83abe
MV
665@end deffn
666
f916cbc4
AW
667@deffn {Scheme Procedure} procedure-property proc key
668@deffnx {C Function} scm_procedure_property (proc, key)
669Return the property of @var{proc} with name @var{key}.
07d83abe
MV
670@end deffn
671
672@deffn {Scheme Procedure} set-procedure-properties! proc alist
673@deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
f916cbc4 674Set @var{proc}'s property list to @var{alist}.
07d83abe
MV
675@end deffn
676
f916cbc4
AW
677@deffn {Scheme Procedure} set-procedure-property! proc key value
678@deffnx {C Function} scm_set_procedure_property_x (proc, key, value)
679In @var{proc}'s property list, set the property named @var{key} to
07d83abe
MV
680@var{value}.
681@end deffn
682
683@cindex procedure documentation
684Documentation for a procedure can be accessed with the procedure
685@code{procedure-documentation}.
686
687@deffn {Scheme Procedure} procedure-documentation proc
688@deffnx {C Function} scm_procedure_documentation (proc)
689Return the documentation string associated with @code{proc}. By
690convention, if a procedure contains more than one expression and the
691first expression is a string constant, that string is assumed to contain
692documentation for that procedure.
693@end deffn
694
07d83abe
MV
695
696@node Procedures with Setters
697@subsection Procedures with Setters
698
699@c FIXME::martin: Review me!
700
701@c FIXME::martin: Document `operator struct'.
702
703@cindex procedure with setter
704@cindex setter
705A @dfn{procedure with setter} is a special kind of procedure which
706normally behaves like any accessor procedure, that is a procedure which
707accesses a data structure. The difference is that this kind of
708procedure has a so-called @dfn{setter} attached, which is a procedure
709for storing something into a data structure.
710
711Procedures with setters are treated specially when the procedure appears
712in the special form @code{set!} (REFFIXME). How it works is best shown
713by example.
714
715Suppose we have a procedure called @code{foo-ref}, which accepts two
716arguments, a value of type @code{foo} and an integer. The procedure
717returns the value stored at the given index in the @code{foo} object.
718Let @code{f} be a variable containing such a @code{foo} data
719structure.@footnote{Working definitions would be:
720@lisp
721(define foo-ref vector-ref)
722(define foo-set! vector-set!)
723(define f (make-vector 2 #f))
724@end lisp
725}
726
727@lisp
728(foo-ref f 0) @result{} bar
729(foo-ref f 1) @result{} braz
730@end lisp
731
732Also suppose that a corresponding setter procedure called
733@code{foo-set!} does exist.
734
735@lisp
736(foo-set! f 0 'bla)
737(foo-ref f 0) @result{} bla
738@end lisp
739
740Now we could create a new procedure called @code{foo}, which is a
741procedure with setter, by calling @code{make-procedure-with-setter} with
742the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
743Let us call this new procedure @code{foo}.
744
745@lisp
746(define foo (make-procedure-with-setter foo-ref foo-set!))
747@end lisp
748
749@code{foo} can from now an be used to either read from the data
750structure stored in @code{f}, or to write into the structure.
751
752@lisp
753(set! (foo f 0) 'dum)
754(foo f 0) @result{} dum
755@end lisp
756
757@deffn {Scheme Procedure} make-procedure-with-setter procedure setter
758@deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
759Create a new procedure which behaves like @var{procedure}, but
760with the associated setter @var{setter}.
761@end deffn
762
763@deffn {Scheme Procedure} procedure-with-setter? obj
764@deffnx {C Function} scm_procedure_with_setter_p (obj)
765Return @code{#t} if @var{obj} is a procedure with an
766associated setter procedure.
767@end deffn
768
769@deffn {Scheme Procedure} procedure proc
770@deffnx {C Function} scm_procedure (proc)
3323ec06
NJ
771Return the procedure of @var{proc}, which must be an
772applicable struct.
07d83abe
MV
773@end deffn
774
775@deffn {Scheme Procedure} setter proc
776Return the setter of @var{proc}, which must be either a procedure with
777setter or an operator struct.
778@end deffn
779
780
781@node Macros
782@subsection Lisp Style Macro Definitions
783
784@cindex macros
785@cindex transformation
786Macros are objects which cause the expression that they appear in to be
787transformed in some way @emph{before} being evaluated. In expressions
788that are intended for macro transformation, the identifier that names
789the relevant macro must appear as the first element, like this:
790
791@lisp
792(@var{macro-name} @var{macro-args} @dots{})
793@end lisp
794
795In Lisp-like languages, the traditional way to define macros is very
796similar to procedure definitions. The key differences are that the
797macro definition body should return a list that describes the
798transformed expression, and that the definition is marked as a macro
799definition (rather than a procedure definition) by the use of a
800different definition keyword: in Lisp, @code{defmacro} rather than
801@code{defun}, and in Scheme, @code{define-macro} rather than
802@code{define}.
803
804@fnindex defmacro
805@fnindex define-macro
806Guile supports this style of macro definition using both @code{defmacro}
807and @code{define-macro}. The only difference between them is how the
808macro name and arguments are grouped together in the definition:
809
810@lisp
811(defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
812@end lisp
813
814@noindent
815is the same as
816
817@lisp
818(define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
819@end lisp
820
821@noindent
822The difference is analogous to the corresponding difference between
823Lisp's @code{defun} and Scheme's @code{define}.
824
825@code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
826distribution, is a good example of macro definition using
827@code{defmacro}:
828
829@lisp
830(defmacro false-if-exception (expr)
831 `(catch #t
832 (lambda () ,expr)
833 (lambda args #f)))
834@end lisp
835
836@noindent
837The effect of this definition is that expressions beginning with the
838identifier @code{false-if-exception} are automatically transformed into
839a @code{catch} expression following the macro definition specification.
840For example:
841
842@lisp
843(false-if-exception (open-input-file "may-not-exist"))
844@equiv{}
845(catch #t
846 (lambda () (open-input-file "may-not-exist"))
847 (lambda args #f))
848@end lisp
849
850
851@node Syntax Rules
852@subsection The R5RS @code{syntax-rules} System
853@cindex R5RS syntax-rules system
854
855R5RS defines an alternative system for macro and syntax transformations
856using the keywords @code{define-syntax}, @code{let-syntax},
857@code{letrec-syntax} and @code{syntax-rules}.
858
859The main difference between the R5RS system and the traditional macros
860of the previous section is how the transformation is specified. In
861R5RS, rather than permitting a macro definition to return an arbitrary
862expression, the transformation is specified in a pattern language that
863
864@itemize @bullet
865@item
866does not require complicated quoting and extraction of components of the
867source expression using @code{caddr} etc.
868
869@item
870is designed such that the bindings associated with identifiers in the
871transformed expression are well defined, and such that it is impossible
872for the transformed expression to construct new identifiers.
873@end itemize
874
875@noindent
876The last point is commonly referred to as being @dfn{hygienic}: the R5RS
877@code{syntax-case} system provides @dfn{hygienic macros}.
878
879For example, the R5RS pattern language for the @code{false-if-exception}
880example of the previous section looks like this:
881
882@lisp
883(syntax-rules ()
884 ((_ expr)
885 (catch #t
886 (lambda () expr)
887 (lambda args #f))))
888@end lisp
889
890@cindex @code{syncase}
891In Guile, the @code{syntax-rules} system is provided by the @code{(ice-9
892syncase)} module. To make these facilities available in your code,
893include the expression @code{(use-syntax (ice-9 syncase))} (@pxref{Using
894Guile Modules}) before the first usage of @code{define-syntax} etc. If
895you are writing a Scheme module, you can alternatively include the form
896@code{#:use-syntax (ice-9 syncase)} in your @code{define-module}
897declaration (@pxref{Creating Guile Modules}).
898
899@menu
900* Pattern Language:: The @code{syntax-rules} pattern language.
901* Define-Syntax:: Top level syntax definitions.
902* Let-Syntax:: Local syntax definitions.
903@end menu
904
905
906@node Pattern Language
907@subsubsection The @code{syntax-rules} Pattern Language
908
909
910@node Define-Syntax
911@subsubsection Top Level Syntax Definitions
912
913define-syntax: The gist is
914
915 (define-syntax <keyword> <transformer-spec>)
916
917makes the <keyword> into a macro so that
918
919 (<keyword> ...)
920
921expands at _compile_ or _read_ time (i.e. before any
922evaluation begins) into some expression that is
923given by the <transformer-spec>.
924
925
926@node Let-Syntax
927@subsubsection Local Syntax Definitions
928
929
930@node Syntax Case
931@subsection Support for the @code{syntax-case} System
932
933
934
935@node Internal Macros
936@subsection Internal Representation of Macros and Syntax
937
f916cbc4
AW
938[FIXME: used to be true. Isn't any more. Use syntax-rules or
939syntax-case please :)]
940
07d83abe
MV
941Internally, Guile uses three different flavors of macros. The three
942flavors are called @dfn{acro} (or @dfn{syntax}), @dfn{macro} and
943@dfn{mmacro}.
944
945Given the expression
946
947@lisp
948(foo @dots{})
949@end lisp
950
951@noindent
952with @code{foo} being some flavor of macro, one of the following things
953will happen when the expression is evaluated.
954
955@itemize @bullet
956@item
957When @code{foo} has been defined to be an @dfn{acro}, the procedure used
958in the acro definition of @code{foo} is passed the whole expression and
959the current lexical environment, and whatever that procedure returns is
960the value of evaluating the expression. You can think of this a
961procedure that receives its argument as an unevaluated expression.
962
963@item
964When @code{foo} has been defined to be a @dfn{macro}, the procedure used
965in the macro definition of @code{foo} is passed the whole expression and
966the current lexical environment, and whatever that procedure returns is
967evaluated again. That is, the procedure should return a valid Scheme
968expression.
969
970@item
971When @code{foo} has been defined to be a @dfn{mmacro}, the procedure
972used in the mmacro definition of `foo' is passed the whole expression
973and the current lexical environment, and whatever that procedure returns
974replaces the original expression. Evaluation then starts over from the
975new expression that has just been returned.
976@end itemize
977
978The key difference between a @dfn{macro} and a @dfn{mmacro} is that the
979expression returned by a @dfn{mmacro} procedure is remembered (or
980@dfn{memoized}) so that the expansion does not need to be done again
981next time the containing code is evaluated.
982
983The primitives @code{procedure->syntax}, @code{procedure->macro} and
984@code{procedure->memoizing-macro} are used to construct acros, macros
985and mmacros respectively. However, if you do not have a very special
986reason to use one of these primitives, you should avoid them: they are
987very specific to Guile's current implementation and therefore likely to
988change. Use @code{defmacro}, @code{define-macro} (@pxref{Macros}) or
989@code{define-syntax} (@pxref{Syntax Rules}) instead. (In low level
990terms, @code{defmacro}, @code{define-macro} and @code{define-syntax} are
991all implemented as mmacros.)
992
993@deffn {Scheme Procedure} procedure->syntax code
994@deffnx {C Function} scm_makacro (code)
995Return a macro which, when a symbol defined to this value appears as the
996first symbol in an expression, returns the result of applying @var{code}
997to the expression and the environment.
998@end deffn
999
1000@deffn {Scheme Procedure} procedure->macro code
1001@deffnx {C Function} scm_makmacro (code)
1002Return a macro which, when a symbol defined to this value appears as the
1003first symbol in an expression, evaluates the result of applying
1004@var{code} to the expression and the environment. For example:
1005
1006@lisp
1007(define trace
1008 (procedure->macro
1009 (lambda (x env)
1010 `(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))
1011
1012(trace @i{foo})
1013@equiv{}
1014(set! @i{foo} (tracef @i{foo} '@i{foo})).
1015@end lisp
1016@end deffn
1017
1018@deffn {Scheme Procedure} procedure->memoizing-macro code
1019@deffnx {C Function} scm_makmmacro (code)
1020Return a macro which, when a symbol defined to this value appears as the
1021first symbol in an expression, evaluates the result of applying
1022@var{code} to the expression and the environment.
1023@code{procedure->memoizing-macro} is the same as
1024@code{procedure->macro}, except that the expression returned by
1025@var{code} replaces the original macro expression in the memoized form
1026of the containing code.
1027@end deffn
1028
1029In the following primitives, @dfn{acro} flavor macros are referred to
1030as @dfn{syntax transformers}.
1031
1032@deffn {Scheme Procedure} macro? obj
1033@deffnx {C Function} scm_macro_p (obj)
3323ec06
NJ
1034Return @code{#t} if @var{obj} is a regular macro, a memoizing macro, a
1035syntax transformer, or a syntax-case macro.
07d83abe
MV
1036@end deffn
1037
1038@deffn {Scheme Procedure} macro-type m
1039@deffnx {C Function} scm_macro_type (m)
3323ec06
NJ
1040Return one of the symbols @code{syntax}, @code{macro},
1041@code{macro!}, or @code{syntax-case}, depending on whether
1042@var{m} is a syntax transformer, a regular macro, a memoizing
1043macro, or a syntax-case macro, respectively. If @var{m} is
1044not a macro, @code{#f} is returned.
07d83abe
MV
1045@end deffn
1046
1047@deffn {Scheme Procedure} macro-name m
1048@deffnx {C Function} scm_macro_name (m)
1049Return the name of the macro @var{m}.
1050@end deffn
1051
1052@deffn {Scheme Procedure} macro-transformer m
1053@deffnx {C Function} scm_macro_transformer (m)
1054Return the transformer of the macro @var{m}.
1055@end deffn
1056
1057@deffn {Scheme Procedure} cons-source xorig x y
1058@deffnx {C Function} scm_cons_source (xorig, x, y)
1059Create and return a new pair whose car and cdr are @var{x} and @var{y}.
1060Any source properties associated with @var{xorig} are also associated
1061with the new pair.
1062@end deffn
1063
1064
1065@c Local Variables:
1066@c TeX-master: "guile.texi"
1067@c End: