update procedure docs for programs, lambda*, case-lambda
[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 @code{case-lambda*} is particularly useful in combination with an
598 obscure @code{lambda*} feature, @code{#:predicate}. @code{lambda*}
599 argument lists may contain a @code{#:predicate @var{expr}} clause at
600 the end -- before the rest argument, if any. This expression is
601 evaluated in the context of all of the arguments, and if false, causes
602 the @code{case-lambda*} expression not to match. This can be used to
603 make a simple form of type dispatch:
604
605 @lisp
606 (define type-of
607 (case-lambda*
608 ((a #:predicate (symbol? a)) 'symbol)
609 ((a #:predicate (string? a)) 'string)
610 ((a) 'unknown)))
611 (type-of 'foo) @result{} symbol
612 (type-of "foo") @result{} string
613 (type-of '(foo)) @result{} unknown
614 @end lisp
615
616 Keyword arguments are possible with @code{case-lambda*}, but they do
617 not contribute to the ``matching'' behavior. That is to say,
618 @code{case-lambda*} matches only on required, optional, and rest
619 arguments, and on the predicate; keyword arguments may be present but
620 do not contribute to the ``success'' of a match. In fact a bad keyword
621 argument list may cause an error to be raised.
622
623 @node Procedure Properties
624 @subsection Procedure Properties and Meta-information
625
626 In addition to the information that is strictly necessary to run,
627 procedures may have other associated information. For example, the
628 name of a procedure is information not for the procedure, but about
629 the procedure. This meta-information can be accessed via the procedure
630 properties interface.
631
632 The first group of procedures in this meta-interface are predicates to
633 test whether a Scheme object is a procedure, or a special procedure,
634 respectively. @code{procedure?} is the most general predicates, it
635 returns @code{#t} for any kind of procedure. @code{closure?} does not
636 return @code{#t} for primitive procedures, and @code{thunk?} only
637 returns @code{#t} for procedures which do not accept any arguments.
638
639 @rnindex procedure?
640 @deffn {Scheme Procedure} procedure? obj
641 @deffnx {C Function} scm_procedure_p (obj)
642 Return @code{#t} if @var{obj} is a procedure.
643 @end deffn
644
645 @deffn {Scheme Procedure} closure? obj
646 @deffnx {C Function} scm_closure_p (obj)
647 Return @code{#t} if @var{obj} is a closure. This category somewhat
648 misnamed, actually, as it applies only to interpreted procedures, not
649 compiled procedures. But since it has historically been used more to
650 select on implementation details than on essence (closure or not), we
651 keep it here for compatibility. Don't use it in new code, though.
652 @end deffn
653
654 @deffn {Scheme Procedure} thunk? obj
655 @deffnx {C Function} scm_thunk_p (obj)
656 Return @code{#t} if @var{obj} is a thunk.
657 @end deffn
658
659 @cindex procedure properties
660 Procedure properties are general properties associated with
661 procedures. These can be the name of a procedure or other relevant
662 information, such as debug hints.
663
664 @deffn {Scheme Procedure} procedure-name proc
665 @deffnx {C Function} scm_procedure_name (proc)
666 Return the name of the procedure @var{proc}
667 @end deffn
668
669 @deffn {Scheme Procedure} procedure-source proc
670 @deffnx {C Function} scm_procedure_source (proc)
671 Return the source of the procedure @var{proc}. Returns @code{#f} if
672 the source code is not available.
673 @end deffn
674
675 @deffn {Scheme Procedure} procedure-environment proc
676 @deffnx {C Function} scm_procedure_environment (proc)
677 Return the environment of the procedure @var{proc}. Very deprecated.
678 @end deffn
679
680 @deffn {Scheme Procedure} procedure-properties proc
681 @deffnx {C Function} scm_procedure_properties (proc)
682 Return the properties associated with @var{proc}, as an association
683 list.
684 @end deffn
685
686 @deffn {Scheme Procedure} procedure-property proc key
687 @deffnx {C Function} scm_procedure_property (proc, key)
688 Return the property of @var{proc} with name @var{key}.
689 @end deffn
690
691 @deffn {Scheme Procedure} set-procedure-properties! proc alist
692 @deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
693 Set @var{proc}'s property list to @var{alist}.
694 @end deffn
695
696 @deffn {Scheme Procedure} set-procedure-property! proc key value
697 @deffnx {C Function} scm_set_procedure_property_x (proc, key, value)
698 In @var{proc}'s property list, set the property named @var{key} to
699 @var{value}.
700 @end deffn
701
702 @cindex procedure documentation
703 Documentation for a procedure can be accessed with the procedure
704 @code{procedure-documentation}.
705
706 @deffn {Scheme Procedure} procedure-documentation proc
707 @deffnx {C Function} scm_procedure_documentation (proc)
708 Return the documentation string associated with @code{proc}. By
709 convention, if a procedure contains more than one expression and the
710 first expression is a string constant, that string is assumed to contain
711 documentation for that procedure.
712 @end deffn
713
714
715 @node Procedures with Setters
716 @subsection Procedures with Setters
717
718 @c FIXME::martin: Review me!
719
720 @c FIXME::martin: Document `operator struct'.
721
722 @cindex procedure with setter
723 @cindex setter
724 A @dfn{procedure with setter} is a special kind of procedure which
725 normally behaves like any accessor procedure, that is a procedure which
726 accesses a data structure. The difference is that this kind of
727 procedure has a so-called @dfn{setter} attached, which is a procedure
728 for storing something into a data structure.
729
730 Procedures with setters are treated specially when the procedure appears
731 in the special form @code{set!} (REFFIXME). How it works is best shown
732 by example.
733
734 Suppose we have a procedure called @code{foo-ref}, which accepts two
735 arguments, a value of type @code{foo} and an integer. The procedure
736 returns the value stored at the given index in the @code{foo} object.
737 Let @code{f} be a variable containing such a @code{foo} data
738 structure.@footnote{Working definitions would be:
739 @lisp
740 (define foo-ref vector-ref)
741 (define foo-set! vector-set!)
742 (define f (make-vector 2 #f))
743 @end lisp
744 }
745
746 @lisp
747 (foo-ref f 0) @result{} bar
748 (foo-ref f 1) @result{} braz
749 @end lisp
750
751 Also suppose that a corresponding setter procedure called
752 @code{foo-set!} does exist.
753
754 @lisp
755 (foo-set! f 0 'bla)
756 (foo-ref f 0) @result{} bla
757 @end lisp
758
759 Now we could create a new procedure called @code{foo}, which is a
760 procedure with setter, by calling @code{make-procedure-with-setter} with
761 the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
762 Let us call this new procedure @code{foo}.
763
764 @lisp
765 (define foo (make-procedure-with-setter foo-ref foo-set!))
766 @end lisp
767
768 @code{foo} can from now an be used to either read from the data
769 structure stored in @code{f}, or to write into the structure.
770
771 @lisp
772 (set! (foo f 0) 'dum)
773 (foo f 0) @result{} dum
774 @end lisp
775
776 @deffn {Scheme Procedure} make-procedure-with-setter procedure setter
777 @deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
778 Create a new procedure which behaves like @var{procedure}, but
779 with the associated setter @var{setter}.
780 @end deffn
781
782 @deffn {Scheme Procedure} procedure-with-setter? obj
783 @deffnx {C Function} scm_procedure_with_setter_p (obj)
784 Return @code{#t} if @var{obj} is a procedure with an
785 associated setter procedure.
786 @end deffn
787
788 @deffn {Scheme Procedure} procedure proc
789 @deffnx {C Function} scm_procedure (proc)
790 Return the procedure of @var{proc}, which must be either a
791 procedure with setter, or an operator struct.
792 @end deffn
793
794 @deffn {Scheme Procedure} setter proc
795 Return the setter of @var{proc}, which must be either a procedure with
796 setter or an operator struct.
797 @end deffn
798
799
800 @node Macros
801 @subsection Lisp Style Macro Definitions
802
803 @cindex macros
804 @cindex transformation
805 Macros are objects which cause the expression that they appear in to be
806 transformed in some way @emph{before} being evaluated. In expressions
807 that are intended for macro transformation, the identifier that names
808 the relevant macro must appear as the first element, like this:
809
810 @lisp
811 (@var{macro-name} @var{macro-args} @dots{})
812 @end lisp
813
814 In Lisp-like languages, the traditional way to define macros is very
815 similar to procedure definitions. The key differences are that the
816 macro definition body should return a list that describes the
817 transformed expression, and that the definition is marked as a macro
818 definition (rather than a procedure definition) by the use of a
819 different definition keyword: in Lisp, @code{defmacro} rather than
820 @code{defun}, and in Scheme, @code{define-macro} rather than
821 @code{define}.
822
823 @fnindex defmacro
824 @fnindex define-macro
825 Guile supports this style of macro definition using both @code{defmacro}
826 and @code{define-macro}. The only difference between them is how the
827 macro name and arguments are grouped together in the definition:
828
829 @lisp
830 (defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
831 @end lisp
832
833 @noindent
834 is the same as
835
836 @lisp
837 (define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
838 @end lisp
839
840 @noindent
841 The difference is analogous to the corresponding difference between
842 Lisp's @code{defun} and Scheme's @code{define}.
843
844 @code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
845 distribution, is a good example of macro definition using
846 @code{defmacro}:
847
848 @lisp
849 (defmacro false-if-exception (expr)
850 `(catch #t
851 (lambda () ,expr)
852 (lambda args #f)))
853 @end lisp
854
855 @noindent
856 The effect of this definition is that expressions beginning with the
857 identifier @code{false-if-exception} are automatically transformed into
858 a @code{catch} expression following the macro definition specification.
859 For example:
860
861 @lisp
862 (false-if-exception (open-input-file "may-not-exist"))
863 @equiv{}
864 (catch #t
865 (lambda () (open-input-file "may-not-exist"))
866 (lambda args #f))
867 @end lisp
868
869
870 @node Syntax Rules
871 @subsection The R5RS @code{syntax-rules} System
872 @cindex R5RS syntax-rules system
873
874 R5RS defines an alternative system for macro and syntax transformations
875 using the keywords @code{define-syntax}, @code{let-syntax},
876 @code{letrec-syntax} and @code{syntax-rules}.
877
878 The main difference between the R5RS system and the traditional macros
879 of the previous section is how the transformation is specified. In
880 R5RS, rather than permitting a macro definition to return an arbitrary
881 expression, the transformation is specified in a pattern language that
882
883 @itemize @bullet
884 @item
885 does not require complicated quoting and extraction of components of the
886 source expression using @code{caddr} etc.
887
888 @item
889 is designed such that the bindings associated with identifiers in the
890 transformed expression are well defined, and such that it is impossible
891 for the transformed expression to construct new identifiers.
892 @end itemize
893
894 @noindent
895 The last point is commonly referred to as being @dfn{hygienic}: the R5RS
896 @code{syntax-case} system provides @dfn{hygienic macros}.
897
898 For example, the R5RS pattern language for the @code{false-if-exception}
899 example of the previous section looks like this:
900
901 @lisp
902 (syntax-rules ()
903 ((_ expr)
904 (catch #t
905 (lambda () expr)
906 (lambda args #f))))
907 @end lisp
908
909 @cindex @code{syncase}
910 In Guile, the @code{syntax-rules} system is provided by the @code{(ice-9
911 syncase)} module. To make these facilities available in your code,
912 include the expression @code{(use-syntax (ice-9 syncase))} (@pxref{Using
913 Guile Modules}) before the first usage of @code{define-syntax} etc. If
914 you are writing a Scheme module, you can alternatively include the form
915 @code{#:use-syntax (ice-9 syncase)} in your @code{define-module}
916 declaration (@pxref{Creating Guile Modules}).
917
918 @menu
919 * Pattern Language:: The @code{syntax-rules} pattern language.
920 * Define-Syntax:: Top level syntax definitions.
921 * Let-Syntax:: Local syntax definitions.
922 @end menu
923
924
925 @node Pattern Language
926 @subsubsection The @code{syntax-rules} Pattern Language
927
928
929 @node Define-Syntax
930 @subsubsection Top Level Syntax Definitions
931
932 define-syntax: The gist is
933
934 (define-syntax <keyword> <transformer-spec>)
935
936 makes the <keyword> into a macro so that
937
938 (<keyword> ...)
939
940 expands at _compile_ or _read_ time (i.e. before any
941 evaluation begins) into some expression that is
942 given by the <transformer-spec>.
943
944
945 @node Let-Syntax
946 @subsubsection Local Syntax Definitions
947
948
949 @node Syntax Case
950 @subsection Support for the @code{syntax-case} System
951
952
953
954 @node Internal Macros
955 @subsection Internal Representation of Macros and Syntax
956
957 [FIXME: used to be true. Isn't any more. Use syntax-rules or
958 syntax-case please :)]
959
960 Internally, Guile uses three different flavors of macros. The three
961 flavors are called @dfn{acro} (or @dfn{syntax}), @dfn{macro} and
962 @dfn{mmacro}.
963
964 Given the expression
965
966 @lisp
967 (foo @dots{})
968 @end lisp
969
970 @noindent
971 with @code{foo} being some flavor of macro, one of the following things
972 will happen when the expression is evaluated.
973
974 @itemize @bullet
975 @item
976 When @code{foo} has been defined to be an @dfn{acro}, the procedure used
977 in the acro definition of @code{foo} is passed the whole expression and
978 the current lexical environment, and whatever that procedure returns is
979 the value of evaluating the expression. You can think of this a
980 procedure that receives its argument as an unevaluated expression.
981
982 @item
983 When @code{foo} has been defined to be a @dfn{macro}, the procedure used
984 in the macro definition of @code{foo} is passed the whole expression and
985 the current lexical environment, and whatever that procedure returns is
986 evaluated again. That is, the procedure should return a valid Scheme
987 expression.
988
989 @item
990 When @code{foo} has been defined to be a @dfn{mmacro}, the procedure
991 used in the mmacro definition of `foo' is passed the whole expression
992 and the current lexical environment, and whatever that procedure returns
993 replaces the original expression. Evaluation then starts over from the
994 new expression that has just been returned.
995 @end itemize
996
997 The key difference between a @dfn{macro} and a @dfn{mmacro} is that the
998 expression returned by a @dfn{mmacro} procedure is remembered (or
999 @dfn{memoized}) so that the expansion does not need to be done again
1000 next time the containing code is evaluated.
1001
1002 The primitives @code{procedure->syntax}, @code{procedure->macro} and
1003 @code{procedure->memoizing-macro} are used to construct acros, macros
1004 and mmacros respectively. However, if you do not have a very special
1005 reason to use one of these primitives, you should avoid them: they are
1006 very specific to Guile's current implementation and therefore likely to
1007 change. Use @code{defmacro}, @code{define-macro} (@pxref{Macros}) or
1008 @code{define-syntax} (@pxref{Syntax Rules}) instead. (In low level
1009 terms, @code{defmacro}, @code{define-macro} and @code{define-syntax} are
1010 all implemented as mmacros.)
1011
1012 @deffn {Scheme Procedure} procedure->syntax code
1013 @deffnx {C Function} scm_makacro (code)
1014 Return a macro which, when a symbol defined to this value appears as the
1015 first symbol in an expression, returns the result of applying @var{code}
1016 to the expression and the environment.
1017 @end deffn
1018
1019 @deffn {Scheme Procedure} procedure->macro code
1020 @deffnx {C Function} scm_makmacro (code)
1021 Return a macro which, when a symbol defined to this value appears as the
1022 first symbol in an expression, evaluates the result of applying
1023 @var{code} to the expression and the environment. For example:
1024
1025 @lisp
1026 (define trace
1027 (procedure->macro
1028 (lambda (x env)
1029 `(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))
1030
1031 (trace @i{foo})
1032 @equiv{}
1033 (set! @i{foo} (tracef @i{foo} '@i{foo})).
1034 @end lisp
1035 @end deffn
1036
1037 @deffn {Scheme Procedure} procedure->memoizing-macro code
1038 @deffnx {C Function} scm_makmmacro (code)
1039 Return a macro which, when a symbol defined to this value appears as the
1040 first symbol in an expression, evaluates the result of applying
1041 @var{code} to the expression and the environment.
1042 @code{procedure->memoizing-macro} is the same as
1043 @code{procedure->macro}, except that the expression returned by
1044 @var{code} replaces the original macro expression in the memoized form
1045 of the containing code.
1046 @end deffn
1047
1048 In the following primitives, @dfn{acro} flavor macros are referred to
1049 as @dfn{syntax transformers}.
1050
1051 @deffn {Scheme Procedure} macro? obj
1052 @deffnx {C Function} scm_macro_p (obj)
1053 Return @code{#t} if @var{obj} is a regular macro, a memoizing macro or a
1054 syntax transformer.
1055 @end deffn
1056
1057 @deffn {Scheme Procedure} macro-type m
1058 @deffnx {C Function} scm_macro_type (m)
1059 Return one of the symbols @code{syntax}, @code{macro} or
1060 @code{macro!}, depending on whether @var{m} is a syntax
1061 transformer, a regular macro, or a memoizing macro,
1062 respectively. If @var{m} is not a macro, @code{#f} is
1063 returned.
1064 @end deffn
1065
1066 @deffn {Scheme Procedure} macro-name m
1067 @deffnx {C Function} scm_macro_name (m)
1068 Return the name of the macro @var{m}.
1069 @end deffn
1070
1071 @deffn {Scheme Procedure} macro-transformer m
1072 @deffnx {C Function} scm_macro_transformer (m)
1073 Return the transformer of the macro @var{m}.
1074 @end deffn
1075
1076 @deffn {Scheme Procedure} cons-source xorig x y
1077 @deffnx {C Function} scm_cons_source (xorig, x, y)
1078 Create and return a new pair whose car and cdr are @var{x} and @var{y}.
1079 Any source properties associated with @var{xorig} are also associated
1080 with the new pair.
1081 @end deffn
1082
1083
1084 @c Local Variables:
1085 @c TeX-master: "guile.texi"
1086 @c End: