merge from master to elisp
[bpt/guile.git] / doc / ref / api-procedures.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009
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.
14 * Compiled Procedures:: Scheme procedures can be compiled.
15 * Optional Arguments:: Handling keyword, optional and rest arguments.
16 * Case-lambda:: One function, multiple arities.
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
30 A @code{lambda} expression evaluates to a procedure. The environment
31 which is in effect when a @code{lambda} expression is evaluated is
32 enclosed in the newly created procedure, this is referred to as a
33 @dfn{closure} (@pxref{About Closure}).
34
35 When a procedure created by @code{lambda} is called with some actual
36 arguments, the environment enclosed in the procedure is extended by
37 binding the variables named in the formal argument list to new locations
38 and storing the actual arguments into these locations. Then the body of
39 the @code{lambda} expression is evaluation sequentially. The result of
40 the last expression in the procedure body is then the result of the
41 procedure invocation.
42
43 The 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
51 The fact that the environment in effect when creating a procedure is
52 enclosed 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
64 following table.
65
66 @table @code
67 @item (@var{variable1} @dots{})
68 The procedure takes a fixed number of arguments; when the procedure is
69 called, the arguments will be stored into the newly created location for
70 the formal variables.
71 @item @var{variable}
72 The procedure takes any number of arguments; when the procedure is
73 called, the sequence of actual arguments will converted into a list and
74 stored into the newly created location for the formal variable.
75 @item (@var{variable1} @dots{} @var{variablen} . @var{variablen+1})
76 If a space-delimited period precedes the last variable, then the
77 procedure takes @var{n} or more variables where @var{n} is the number
78 of formal arguments before the period. There must be at least one
79 argument before the period. The first @var{n} actual arguments will be
80 stored into the newly allocated locations for the first @var{n} formal
81 arguments and the sequence of the remaining actual arguments is
82 converted into a list and the stored into the location for the last
83 formal argument. If there are exactly @var{n} actual arguments, the
84 empty list is stored into the location of the last formal argument.
85 @end table
86
87 The list in @var{variable} or @var{variablen+1} is always newly
88 created and the procedure can modify it if desired. This is the case
89 even when the procedure is invoked via @code{apply}, the required part
90 of the list argument there will be copied (@pxref{Fly Evaluation,,
91 Procedures for On the Fly Evaluation}).
92
93 @var{body} is a sequence of Scheme expressions which are evaluated in
94 order 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
102 Procedures written in C can be registered for use from Scheme,
103 provided 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
105 useful 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)
109 Register a C procedure @var{FCN} as a ``subr'' --- a primitive
110 subroutine that can be called from Scheme. It will be associated with
111 the given @var{name} but no environment binding will be created. The
112 arguments @var{req}, @var{opt} and @var{rst} specify the number of
113 required, optional and ``rest'' arguments respectively. The total
114 number of these arguments should match the actual number of arguments
115 to @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)
121 Register a C procedure @var{FCN}, as for @code{scm_c_make_gsubr}
122 above, and additionally create a top-level Scheme binding for the
123 procedure in the ``current environment'' using @code{scm_define}.
124 @code{scm_c_define_gsubr} returns a handle for the procedure in the
125 same way as @code{scm_c_make_gsubr}, which is usually not further
126 required.
127 @end deftypefun
128
129 @code{scm_c_make_gsubr} and @code{scm_c_define_gsubr} automatically
130 use @code{scm_c_make_subr} and also @code{scm_makcclo} if necessary.
131 It is advisable to use the gsubr variants since they provide a
132 slightly higher-level abstraction of the Guile implementation.
133
134 @node Compiled Procedures
135 @subsection Compiled Procedures
136
137 In Guile, procedures can be executed by directly interpreting their
138 source code. Scheme source code is a set of nested lists, after all,
139 with each list representing a procedure call.
140
141 Most procedures are compiled, however. This means that Guile has done
142 some pre-computation on the procedure, to determine what it will need
143 to do each time the procedure runs. Compiled procedures run faster
144 than interpreted procedures.
145
146 Loading files is the normal way that compiled procedures come to
147 being. If Guile sees that a file is uncompiled, or that its compiled
148 file is out of date, it will attempt to compile the file when it is
149 loaded, and save the result to disk. Procedures can be compiled at
150 runtime as well. @xref{Read/Load/Eval/Compile}, for more information
151 on runtime compilation.
152
153 Compiled procedures, also known as @dfn{programs}, respond all
154 procedures that operate on procedures. In addition, there are a few
155 more accessors for low-level details on programs.
156
157 Most people won't need to use the routines described in this section,
158 but it's good to have them documented. You'll have to include the
159 appropriate module first, though:
160
161 @example
162 (use-modules (system vm program))
163 @end example
164
165 @deffn {Scheme Procedure} program? obj
166 @deffnx {C Function} scm_program_p (obj)
167 Returns @code{#t} iff @var{obj} is a compiled procedure.
168 @end deffn
169
170 @deffn {Scheme Procedure} program-objcode program
171 @deffnx {C Function} scm_program_objcode (program)
172 Returns the object code associated with this program. @xref{Bytecode
173 and Objcode}, for more information.
174 @end deffn
175
176 @deffn {Scheme Procedure} program-objects program
177 @deffnx {C Function} scm_program_objects (program)
178 Returns the ``object table'' associated with this program, as a
179 vector. @xref{VM Programs}, for more information.
180 @end deffn
181
182 @deffn {Scheme Procedure} program-module program
183 @deffnx {C Function} scm_program_module (program)
184 Returns the module that was current when this program was created. Can
185 return @code{#f} if the compiler could determine that this information
186 was unnecessary.
187 @end deffn
188
189 @deffn {Scheme Procedure} program-free-variables program
190 @deffnx {C Function} scm_program_free_variables (program)
191 Returns the set of free variables that this program captures in its
192 closure, as a vector. If a closure is code with data, you can get the
193 code from @code{program-objcode}, and the data via
194 @code{program-free-variables}.
195
196 Some of the values captured are actually in variable ``boxes''.
197 @xref{Variables and the VM}, for more information.
198
199 Users must not modify the returned value unless they think they're
200 really clever.
201 @end deffn
202
203 @deffn {Scheme Procedure} program-meta program
204 @deffnx {C Function} scm_program_meta (program)
205 Return the metadata thunk of @var{program}, or @code{#f} if it has no
206 metadata.
207
208 When called, a metadata thunk returns a list of the following form:
209 @code{(@var{bindings} @var{sources} @var{arities} . @var{properties})}. The format
210 of each of these elements is discussed below.
211 @end deffn
212
213 @deffn {Scheme Procedure} program-bindings program
214 @deffnx {Scheme Procedure} make-binding name boxed? index start end
215 @deffnx {Scheme Procedure} binding:name binding
216 @deffnx {Scheme Procedure} binding:boxed? binding
217 @deffnx {Scheme Procedure} binding:index binding
218 @deffnx {Scheme Procedure} binding:start binding
219 @deffnx {Scheme Procedure} binding:end binding
220 Bindings annotations for programs, along with their accessors.
221
222 Bindings declare names and liveness extents for block-local variables.
223 The best way to see what these are is to play around with them at a
224 REPL. @xref{VM Concepts}, for more information.
225
226 Note that bindings information is stored in a program as part of its
227 metadata thunk, so including it in the generated object code does not
228 impose a runtime performance penalty.
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
236 Source location annotations for programs, along with their accessors.
237
238 Source location information propagates through the compiler and ends
239 up being serialized to the program's metadata. This information is
240 keyed by the offset of the instruction pointer within the object code
241 of the program. Specifically, it is keyed on the @code{ip} @emph{just
242 following} an instruction, so that backtraces can find the source
243 location of a call that is in progress.
244 @end deffn
245
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
256 Accessors for a representation of the ``arity'' of a program.
257
258 The 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
260 could access that number of required arguments via @code{(arity:nreq
261 (program-arities (lambda (x) x)))}. Similarly, @code{arity:nopt} gets
262 the number of optional arguments, and @code{arity:rest?} returns a true
263 value if the procedure has a rest arg.
264
265 @code{arity:kw} returns a list of @code{(@var{kw} . @var{idx})} pairs,
266 if the procedure has keyword arguments. The @var{idx} refers to the
267 @var{idx}th local variable; @xref{Variables and the VM}, for more
268 information. Finally @code{arity:allow-other-keys?} returns a true
269 value if other keys are allowed. @xref{Optional Arguments}, for more
270 information.
271
272 So what about @code{arity:start} and @code{arity:end}, then? They
273 return the range of bytes in the program's bytecode for which a given
274 arity is valid. You see, a procedure can actually have more than one
275 arity. The question, ``what is a procedure's arity'' only really makes
276 sense at certain points in the program, delimited by these
277 @code{arity:start} and @code{arity:end} values.
278 @end deffn
279
280 @deffn {Scheme Procedure} program-properties program
281 Return the properties of a @code{program} as an association list,
282 keyed by property name (a symbol).
283
284 Some 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
292 Access a program's property by name, returning @code{#f} if not found.
293 @end deffn
294
295 @deffn {Scheme Procedure} program-documentation program
296 @deffnx {Scheme Procedure} program-name program
297 Accessors for specific properties.
298 @end deffn
299
300 @node Optional Arguments
301 @subsection Optional Arguments
302
303 Scheme procedures, as defined in R5RS, can either handle a fixed number
304 of actual arguments, or a fixed number of actual arguments followed by
305 arbitrarily many additional arguments. Writing procedures of variable
306 arity can be useful, but unfortunately, the syntactic means for handling
307 argument lists of varying length is a bit inconvenient. It is possible
308 to give names to the fixed number of arguments, but the remaining
309 (optional) arguments can be only referenced as a list of values
310 (@pxref{Lambda}).
311
312 For this reason, Guile provides an extension to @code{lambda},
313 @code{lambda*}, which allows the user to define procedures with
314 optional and keyword arguments. In addition, Guile's virtual machine
315 has low-level support for optional and keyword argument dispatch.
316 Calls to procedures with optional and keyword arguments can be made
317 cheaply, without allocating a rest list.
318
319 @menu
320 * lambda* and define*:: Creating advanced argument handling procedures.
321 * ice-9 optargs:: (ice-9 optargs) provides some utilities.
322 @end menu
323
324
325 @node lambda* and define*
326 @subsubsection lambda* and define*.
327
328 @code{lambda*} is like @code{lambda}, except with some extensions to
329 allow optional and keyword arguments.
330
331 @deffn {library syntax} lambda* ([var@dots{}] @* [#:optional vardef@dots{}] @* [#:key vardef@dots{} [#:allow-other-keys]] @* [#:rest var | . var]) @* body
332 @sp 1
333 Create a procedure which takes optional and/or keyword arguments
334 specified with @code{#:optional} and @code{#:key}. For example,
335
336 @lisp
337 (lambda* (a b #:optional c d . e) '())
338 @end lisp
339
340 is a procedure with fixed arguments @var{a} and @var{b}, optional
341 arguments @var{c} and @var{d}, and rest argument @var{e}. If the
342 optional arguments are omitted in a call, the variables for them are
343 bound to @code{#f}.
344
345 @fnindex define*
346 Likewise, @code{define*} is syntactic sugar for defining procedures
347 using @code{lambda*}.
348
349 @code{lambda*} can also make procedures with keyword arguments. For
350 example, a procedure defined like this:
351
352 @lisp
353 (define* (sir-yes-sir #:key action how-high)
354 (list action how-high))
355 @end lisp
356
357 can 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
360 arguments are given as keywords are bound to values (and those not
361 given are @code{#f}).
362
363 Optional and keyword arguments can also have default values to take
364 when not present in a call, by giving a two-element list of variable
365 name and expression. For example in
366
367 @lisp
368 (define* (frob foo #:optional (bar 42) #:key (baz 73))
369 (list foo bar baz))
370 @end lisp
371
372 @var{foo} is a fixed argument, @var{bar} is an optional argument with
373 default value 42, and baz is a keyword argument with default value 73.
374 Default value expressions are not evaluated unless they are needed,
375 and until the procedure is called.
376
377 Normally it's an error if a call has keywords other than those
378 specified by @code{#:key}, but adding @code{#:allow-other-keys} to the
379 definition (after the keyword argument declarations) will ignore
380 unknown keywords.
381
382 If a call has a keyword given twice, the last value is used. For
383 example,
384
385 @lisp
386 (define* (flips #:key (heads 0) (tails 0))
387 (display (list heads tails)))
388
389 (flips #:heads 37 #:tails 42 #:heads 99)
390 @print{} (99 42)
391 @end lisp
392
393 @code{#:rest} is a synonym for the dotted syntax rest argument. The
394 argument lists @code{(a . b)} and @code{(a #:rest b)} are equivalent
395 in all respects. This is provided for more similarity to DSSSL,
396 MIT-Scheme and Kawa among others, as well as for refugees from other
397 Lisp dialects.
398
399 When @code{#:key} is used together with a rest argument, the keyword
400 parameters in a call all remain in the rest list. This is the same as
401 Common Lisp. For example,
402
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
411 successively, from left to right. This means default expressions can
412 refer back to prior parameters, for example
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
420
421 The exception to this left-to-right scoping rule is the rest argument.
422 If there is a rest argument, it is bound after the optional arguments,
423 but before the keyword arguments.
424 @end deffn
425
426
427 @node ice-9 optargs
428 @subsubsection (ice-9 optargs)
429
430 Before Guile 2.0, @code{lambda*} and @code{define*} were implemented
431 using macros that processed rest list arguments. This was not optimal,
432 as calling procedures with optional arguments had to allocate rest
433 lists at every procedure invocation. Guile 2.0 improved this
434 situation by bringing optional and keyword arguments into Guile's
435 core.
436
437 However there are occasions in which you have a list and want to parse
438 it for optional or keyword arguments. Guile's @code{(ice-9 optargs)}
439 provides some macros to help with that task.
440
441 The syntax @code{let-optional} and @code{let-optional*} are for
442 destructuring rest argument lists and giving names to the various list
443 elements. @code{let-optional} binds all variables simultaneously, while
444 @code{let-optional*} binds them sequentially, consistent with @code{let}
445 and @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{}
449 These two macros give you an optional argument interface that is very
450 @dfn{Schemey} and introduces no fancy syntax. They are compatible with
451 the 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
454 procedures these are used from. The items in @var{rest-arg} are
455 sequentially bound to the variable names are given. When @var{rest-arg}
456 runs 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
458 bound to whatever may have been left of @var{rest-arg}.
459
460 After binding the variables, the expressions @var{expr} @dots{} are
461 evaluated in order.
462 @end deffn
463
464 Similarly, @code{let-keywords} and @code{let-keywords*} extract values
465 from keyword style argument lists, binding local variables to those
466 values or to defaults.
467
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
473 variables to be set (by name) from the keyword values. The @var{body}
474 forms are then evaluated and the last is the result. An example will
475 make the syntax clearest,
476
477 @example
478 (define args '(#:xyzzy "hello" #:foo "world"))
479
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
488
489 The 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
494 keywords are allowed in the @var{args} list. When true other keys are
495 ignored (such as @code{#:xyzzy} in the example), when @code{#f} an
496 error is thrown for anything unknown.
497 @end deffn
498
499 @code{(ice-9 optargs)} also provides some more @code{define*} sugar,
500 which 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}
503 exist for defining macros with the improved argument list handling
504 possibilities. The @code{-public} versions not only define the
505 procedures/macros, but also export them from the current module.
506
507 @deffn {library syntax} define*-public formals body
508 Like a mix of @code{define*} and @code{define-public}.
509 @end deffn
510
511 @deffn {library syntax} defmacro* name formals body
512 @deffnx {library syntax} defmacro*-public name formals body
513 These are just like @code{defmacro} and @code{defmacro-public} except that they
514 take @code{lambda*}-style extended parameter lists, where @code{#:optional},
515 @code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
516 semantics. Here is an example of a macro with an optional argument:
517
518 @lisp
519 (defmacro* transmorgify (a #:optional b)
520 (a 1))
521 @end lisp
522 @end deffn
523
524 @node Case-lambda
525 @subsection Case-lambda
526 @cindex SRFI-16
527 @cindex variable arity
528 @cindex arity, variable
529
530 R5RS's rest arguments are indeed useful and very general, but they
531 often aren't the most appropriate or efficient means to get the job
532 done. For example, @code{lambda*} is a much better solution to the
533 optional argument problem than @code{lambda} with rest arguments.
534
535 @fnindex case-lambda
536 Likewise, @code{case-lambda} works well for when you want one
537 procedure to do double duty (or triple, or ...), without the penalty
538 of consing a rest list.
539
540 For 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
554 The value returned by a @code{case-lambda} form is a procedure which
555 matches the number of actual arguments against the formals in the
556 various clauses, in order. The first matching clause is selected, the
557 corresponding values from the actual parameter list are bound to the
558 variable names in the clauses and the body of the clause is evaluated.
559 If no clause matches, an error is signalled.
560
561 The syntax of the @code{case-lambda} form is defined in the following
562 EBNF grammar. @dfn{Formals} means a formal argument list just like
563 with @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
578 Rest 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*
591 Also, for completeness. Guile defines @code{case-lambda*} as well,
592 which is like @code{case-lambda}, except with @code{lambda*} clauses.
593 A @code{case-lambda*} clause matches if the arguments fill the
594 required arguments, but are not too many for the optional and/or rest
595 arguments.
596
597 Keyword arguments are possible with @code{case-lambda*}, but they do
598 not contribute to the ``matching'' behavior. That is to say,
599 @code{case-lambda*} matches only on required, optional, and rest
600 arguments, and on the predicate; keyword arguments may be present but
601 do not contribute to the ``success'' of a match. In fact a bad keyword
602 argument list may cause an error to be raised.
603
604 @node Procedure Properties
605 @subsection Procedure Properties and Meta-information
606
607 In addition to the information that is strictly necessary to run,
608 procedures may have other associated information. For example, the
609 name of a procedure is information not for the procedure, but about
610 the procedure. This meta-information can be accessed via the procedure
611 properties interface.
612
613 The first group of procedures in this meta-interface are predicates to
614 test whether a Scheme object is a procedure, or a special procedure,
615 respectively. @code{procedure?} is the most general predicates, it
616 returns @code{#t} for any kind of procedure. @code{closure?} does not
617 return @code{#t} for primitive procedures, and @code{thunk?} only
618 returns @code{#t} for procedures which do not accept any arguments.
619
620 @rnindex procedure?
621 @deffn {Scheme Procedure} procedure? obj
622 @deffnx {C Function} scm_procedure_p (obj)
623 Return @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)
628 Return @code{#t} if @var{obj} is a closure. This category somewhat
629 misnamed, actually, as it applies only to interpreted procedures, not
630 compiled procedures. But since it has historically been used more to
631 select on implementation details than on essence (closure or not), we
632 keep it here for compatibility. Don't use it in new code, though.
633 @end deffn
634
635 @deffn {Scheme Procedure} thunk? obj
636 @deffnx {C Function} scm_thunk_p (obj)
637 Return @code{#t} if @var{obj} is a thunk.
638 @end deffn
639
640 @cindex procedure properties
641 Procedure properties are general properties associated with
642 procedures. These can be the name of a procedure or other relevant
643 information, such as debug hints.
644
645 @deffn {Scheme Procedure} procedure-name proc
646 @deffnx {C Function} scm_procedure_name (proc)
647 Return 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)
652 Return the source of the procedure @var{proc}. Returns @code{#f} if
653 the source code is not available.
654 @end deffn
655
656 @deffn {Scheme Procedure} procedure-environment proc
657 @deffnx {C Function} scm_procedure_environment (proc)
658 Return the environment of the procedure @var{proc}. Very deprecated.
659 @end deffn
660
661 @deffn {Scheme Procedure} procedure-properties proc
662 @deffnx {C Function} scm_procedure_properties (proc)
663 Return the properties associated with @var{proc}, as an association
664 list.
665 @end deffn
666
667 @deffn {Scheme Procedure} procedure-property proc key
668 @deffnx {C Function} scm_procedure_property (proc, key)
669 Return the property of @var{proc} with name @var{key}.
670 @end deffn
671
672 @deffn {Scheme Procedure} set-procedure-properties! proc alist
673 @deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
674 Set @var{proc}'s property list to @var{alist}.
675 @end deffn
676
677 @deffn {Scheme Procedure} set-procedure-property! proc key value
678 @deffnx {C Function} scm_set_procedure_property_x (proc, key, value)
679 In @var{proc}'s property list, set the property named @var{key} to
680 @var{value}.
681 @end deffn
682
683 @cindex procedure documentation
684 Documentation 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)
689 Return the documentation string associated with @code{proc}. By
690 convention, if a procedure contains more than one expression and the
691 first expression is a string constant, that string is assumed to contain
692 documentation for that procedure.
693 @end deffn
694
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
705 A @dfn{procedure with setter} is a special kind of procedure which
706 normally behaves like any accessor procedure, that is a procedure which
707 accesses a data structure. The difference is that this kind of
708 procedure has a so-called @dfn{setter} attached, which is a procedure
709 for storing something into a data structure.
710
711 Procedures with setters are treated specially when the procedure appears
712 in the special form @code{set!} (REFFIXME). How it works is best shown
713 by example.
714
715 Suppose we have a procedure called @code{foo-ref}, which accepts two
716 arguments, a value of type @code{foo} and an integer. The procedure
717 returns the value stored at the given index in the @code{foo} object.
718 Let @code{f} be a variable containing such a @code{foo} data
719 structure.@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
732 Also 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
740 Now we could create a new procedure called @code{foo}, which is a
741 procedure with setter, by calling @code{make-procedure-with-setter} with
742 the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
743 Let 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
750 structure 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)
759 Create a new procedure which behaves like @var{procedure}, but
760 with 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)
765 Return @code{#t} if @var{obj} is a procedure with an
766 associated setter procedure.
767 @end deffn
768
769 @deffn {Scheme Procedure} procedure proc
770 @deffnx {C Function} scm_procedure (proc)
771 Return the procedure of @var{proc}, which must be either a
772 procedure with setter, or an operator struct.
773 @end deffn
774
775 @deffn {Scheme Procedure} setter proc
776 Return the setter of @var{proc}, which must be either a procedure with
777 setter 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
786 Macros are objects which cause the expression that they appear in to be
787 transformed in some way @emph{before} being evaluated. In expressions
788 that are intended for macro transformation, the identifier that names
789 the 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
795 In Lisp-like languages, the traditional way to define macros is very
796 similar to procedure definitions. The key differences are that the
797 macro definition body should return a list that describes the
798 transformed expression, and that the definition is marked as a macro
799 definition (rather than a procedure definition) by the use of a
800 different 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
806 Guile supports this style of macro definition using both @code{defmacro}
807 and @code{define-macro}. The only difference between them is how the
808 macro 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
815 is the same as
816
817 @lisp
818 (define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
819 @end lisp
820
821 @noindent
822 The difference is analogous to the corresponding difference between
823 Lisp's @code{defun} and Scheme's @code{define}.
824
825 @code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
826 distribution, 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
837 The effect of this definition is that expressions beginning with the
838 identifier @code{false-if-exception} are automatically transformed into
839 a @code{catch} expression following the macro definition specification.
840 For 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
855 R5RS defines an alternative system for macro and syntax transformations
856 using the keywords @code{define-syntax}, @code{let-syntax},
857 @code{letrec-syntax} and @code{syntax-rules}.
858
859 The main difference between the R5RS system and the traditional macros
860 of the previous section is how the transformation is specified. In
861 R5RS, rather than permitting a macro definition to return an arbitrary
862 expression, the transformation is specified in a pattern language that
863
864 @itemize @bullet
865 @item
866 does not require complicated quoting and extraction of components of the
867 source expression using @code{caddr} etc.
868
869 @item
870 is designed such that the bindings associated with identifiers in the
871 transformed expression are well defined, and such that it is impossible
872 for the transformed expression to construct new identifiers.
873 @end itemize
874
875 @noindent
876 The last point is commonly referred to as being @dfn{hygienic}: the R5RS
877 @code{syntax-case} system provides @dfn{hygienic macros}.
878
879 For example, the R5RS pattern language for the @code{false-if-exception}
880 example 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}
891 In Guile, the @code{syntax-rules} system is provided by the @code{(ice-9
892 syncase)} module. To make these facilities available in your code,
893 include the expression @code{(use-syntax (ice-9 syncase))} (@pxref{Using
894 Guile Modules}) before the first usage of @code{define-syntax} etc. If
895 you are writing a Scheme module, you can alternatively include the form
896 @code{#:use-syntax (ice-9 syncase)} in your @code{define-module}
897 declaration (@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
913 define-syntax: The gist is
914
915 (define-syntax <keyword> <transformer-spec>)
916
917 makes the <keyword> into a macro so that
918
919 (<keyword> ...)
920
921 expands at _compile_ or _read_ time (i.e. before any
922 evaluation begins) into some expression that is
923 given 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
938 [FIXME: used to be true. Isn't any more. Use syntax-rules or
939 syntax-case please :)]
940
941 Internally, Guile uses three different flavors of macros. The three
942 flavors are called @dfn{acro} (or @dfn{syntax}), @dfn{macro} and
943 @dfn{mmacro}.
944
945 Given the expression
946
947 @lisp
948 (foo @dots{})
949 @end lisp
950
951 @noindent
952 with @code{foo} being some flavor of macro, one of the following things
953 will happen when the expression is evaluated.
954
955 @itemize @bullet
956 @item
957 When @code{foo} has been defined to be an @dfn{acro}, the procedure used
958 in the acro definition of @code{foo} is passed the whole expression and
959 the current lexical environment, and whatever that procedure returns is
960 the value of evaluating the expression. You can think of this a
961 procedure that receives its argument as an unevaluated expression.
962
963 @item
964 When @code{foo} has been defined to be a @dfn{macro}, the procedure used
965 in the macro definition of @code{foo} is passed the whole expression and
966 the current lexical environment, and whatever that procedure returns is
967 evaluated again. That is, the procedure should return a valid Scheme
968 expression.
969
970 @item
971 When @code{foo} has been defined to be a @dfn{mmacro}, the procedure
972 used in the mmacro definition of `foo' is passed the whole expression
973 and the current lexical environment, and whatever that procedure returns
974 replaces the original expression. Evaluation then starts over from the
975 new expression that has just been returned.
976 @end itemize
977
978 The key difference between a @dfn{macro} and a @dfn{mmacro} is that the
979 expression returned by a @dfn{mmacro} procedure is remembered (or
980 @dfn{memoized}) so that the expansion does not need to be done again
981 next time the containing code is evaluated.
982
983 The primitives @code{procedure->syntax}, @code{procedure->macro} and
984 @code{procedure->memoizing-macro} are used to construct acros, macros
985 and mmacros respectively. However, if you do not have a very special
986 reason to use one of these primitives, you should avoid them: they are
987 very specific to Guile's current implementation and therefore likely to
988 change. Use @code{defmacro}, @code{define-macro} (@pxref{Macros}) or
989 @code{define-syntax} (@pxref{Syntax Rules}) instead. (In low level
990 terms, @code{defmacro}, @code{define-macro} and @code{define-syntax} are
991 all implemented as mmacros.)
992
993 @deffn {Scheme Procedure} procedure->syntax code
994 @deffnx {C Function} scm_makacro (code)
995 Return a macro which, when a symbol defined to this value appears as the
996 first symbol in an expression, returns the result of applying @var{code}
997 to the expression and the environment.
998 @end deffn
999
1000 @deffn {Scheme Procedure} procedure->macro code
1001 @deffnx {C Function} scm_makmacro (code)
1002 Return a macro which, when a symbol defined to this value appears as the
1003 first 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)
1020 Return a macro which, when a symbol defined to this value appears as the
1021 first 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
1026 of the containing code.
1027 @end deffn
1028
1029 In the following primitives, @dfn{acro} flavor macros are referred to
1030 as @dfn{syntax transformers}.
1031
1032 @deffn {Scheme Procedure} macro? obj
1033 @deffnx {C Function} scm_macro_p (obj)
1034 Return @code{#t} if @var{obj} is a regular macro, a memoizing macro or a
1035 syntax transformer.
1036 @end deffn
1037
1038 @deffn {Scheme Procedure} macro-type m
1039 @deffnx {C Function} scm_macro_type (m)
1040 Return one of the symbols @code{syntax}, @code{macro} or
1041 @code{macro!}, depending on whether @var{m} is a syntax
1042 transformer, a regular macro, or a memoizing macro,
1043 respectively. If @var{m} is not a macro, @code{#f} is
1044 returned.
1045 @end deffn
1046
1047 @deffn {Scheme Procedure} macro-name m
1048 @deffnx {C Function} scm_macro_name (m)
1049 Return 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)
1054 Return 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)
1059 Create and return a new pair whose car and cdr are @var{x} and @var{y}.
1060 Any source properties associated with @var{xorig} are also associated
1061 with the new pair.
1062 @end deffn
1063
1064
1065 @c Local Variables:
1066 @c TeX-master: "guile.texi"
1067 @c End: