Update vm.texi's "Instruction Set" section.
[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.
b3da54d1 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009, 2010,
9f17d967 4@c 2011, 2012, 2013 Free Software Foundation, Inc.
07d83abe
MV
5@c See the file guile.texi for copying conditions.
6
e4955559
AW
7@node Procedures
8@section Procedures
07d83abe
MV
9
10@menu
11* Lambda:: Basic procedure creation using lambda.
12* Primitive Procedures:: Procedures defined in C.
00ce5125 13* Compiled Procedures:: Scheme procedures can be compiled.
07d83abe 14* Optional Arguments:: Handling keyword, optional and rest arguments.
f916cbc4 15* Case-lambda:: One function, multiple arities.
18f06db9 16* Higher-Order Functions:: Function that take or return functions.
07d83abe
MV
17* Procedure Properties:: Procedure properties and meta-information.
18* Procedures with Setters:: Procedures with setters.
165b10dd 19* Inlinable Procedures:: Procedures that can be inlined.
07d83abe
MV
20@end menu
21
22
23@node Lambda
24@subsection Lambda: Basic Procedure Creation
25@cindex lambda
26
07d83abe
MV
27A @code{lambda} expression evaluates to a procedure. The environment
28which is in effect when a @code{lambda} expression is evaluated is
29enclosed in the newly created procedure, this is referred to as a
30@dfn{closure} (@pxref{About Closure}).
31
32When a procedure created by @code{lambda} is called with some actual
33arguments, the environment enclosed in the procedure is extended by
34binding the variables named in the formal argument list to new locations
35and storing the actual arguments into these locations. Then the body of
2e4ef7ed 36the @code{lambda} expression is evaluated sequentially. The result of
07d83abe
MV
37the last expression in the procedure body is then the result of the
38procedure invocation.
39
40The following examples will show how procedures can be created using
41@code{lambda}, and what you can do with these procedures.
42
43@lisp
44(lambda (x) (+ x x)) @result{} @r{a procedure}
45((lambda (x) (+ x x)) 4) @result{} 8
46@end lisp
47
48The fact that the environment in effect when creating a procedure is
49enclosed in the procedure is shown with this example:
50
51@lisp
52(define add4
53 (let ((x 4))
54 (lambda (y) (+ x y))))
55(add4 6) @result{} 10
56@end lisp
57
58
59@deffn syntax lambda formals body
60@var{formals} should be a formal argument list as described in the
61following table.
62
63@table @code
64@item (@var{variable1} @dots{})
65The procedure takes a fixed number of arguments; when the procedure is
66called, the arguments will be stored into the newly created location for
67the formal variables.
68@item @var{variable}
69The procedure takes any number of arguments; when the procedure is
70called, the sequence of actual arguments will converted into a list and
71stored into the newly created location for the formal variable.
72@item (@var{variable1} @dots{} @var{variablen} . @var{variablen+1})
73If a space-delimited period precedes the last variable, then the
74procedure takes @var{n} or more variables where @var{n} is the number
75of formal arguments before the period. There must be at least one
76argument before the period. The first @var{n} actual arguments will be
77stored into the newly allocated locations for the first @var{n} formal
78arguments and the sequence of the remaining actual arguments is
79converted into a list and the stored into the location for the last
80formal argument. If there are exactly @var{n} actual arguments, the
81empty list is stored into the location of the last formal argument.
82@end table
83
84The list in @var{variable} or @var{variablen+1} is always newly
85created and the procedure can modify it if desired. This is the case
86even when the procedure is invoked via @code{apply}, the required part
87of the list argument there will be copied (@pxref{Fly Evaluation,,
88Procedures for On the Fly Evaluation}).
89
90@var{body} is a sequence of Scheme expressions which are evaluated in
91order when the procedure is invoked.
92@end deffn
93
94@node Primitive Procedures
95@subsection Primitive Procedures
96@cindex primitives
97@cindex primitive procedures
98
99Procedures written in C can be registered for use from Scheme,
100provided they take only arguments of type @code{SCM} and return
101@code{SCM} values. @code{scm_c_define_gsubr} is likely to be the most
102useful mechanism, combining the process of registration
103(@code{scm_c_make_gsubr}) and definition (@code{scm_define}).
104
105@deftypefun SCM scm_c_make_gsubr (const char *name, int req, int opt, int rst, fcn)
64de6db5 106Register a C procedure @var{fcn} as a ``subr'' --- a primitive
07d83abe
MV
107subroutine that can be called from Scheme. It will be associated with
108the given @var{name} but no environment binding will be created. The
109arguments @var{req}, @var{opt} and @var{rst} specify the number of
110required, optional and ``rest'' arguments respectively. The total
111number of these arguments should match the actual number of arguments
4adf9a7e 112to @var{fcn}, but may not exceed 10. The number of rest arguments should be 0 or 1.
07d83abe
MV
113@code{scm_c_make_gsubr} returns a value of type @code{SCM} which is a
114``handle'' for the procedure.
115@end deftypefun
116
117@deftypefun SCM scm_c_define_gsubr (const char *name, int req, int opt, int rst, fcn)
64de6db5 118Register a C procedure @var{fcn}, as for @code{scm_c_make_gsubr}
07d83abe
MV
119above, and additionally create a top-level Scheme binding for the
120procedure in the ``current environment'' using @code{scm_define}.
121@code{scm_c_define_gsubr} returns a handle for the procedure in the
122same way as @code{scm_c_make_gsubr}, which is usually not further
123required.
124@end deftypefun
125
00ce5125
AW
126@node Compiled Procedures
127@subsection Compiled Procedures
128
7545ddd4
AW
129The evaluation strategy given in @ref{Lambda} describes how procedures
130are @dfn{interpreted}. Interpretation operates directly on expanded
131Scheme source code, recursively calling the evaluator to obtain the
132value of nested expressions.
f916cbc4
AW
133
134Most procedures are compiled, however. This means that Guile has done
7545ddd4
AW
135some pre-computation on the procedure, to determine what it will need to
136do each time the procedure runs. Compiled procedures run faster than
137interpreted procedures.
00ce5125 138
f916cbc4
AW
139Loading files is the normal way that compiled procedures come to
140being. If Guile sees that a file is uncompiled, or that its compiled
141file is out of date, it will attempt to compile the file when it is
142loaded, and save the result to disk. Procedures can be compiled at
143runtime as well. @xref{Read/Load/Eval/Compile}, for more information
144on runtime compilation.
00ce5125 145
5a069042
AW
146Compiled procedures, also known as @dfn{programs}, respond all
147procedures that operate on procedures. In addition, there are a few
46d666d4 148more accessors for low-level details on programs.
5a069042 149
46d666d4
AW
150Most people won't need to use the routines described in this section,
151but it's good to have them documented. You'll have to include the
152appropriate module first, though:
5a069042
AW
153
154@example
155(use-modules (system vm program))
156@end example
157
46d666d4
AW
158@deffn {Scheme Procedure} program? obj
159@deffnx {C Function} scm_program_p (obj)
a4b4fbbd
JE
160Returns @code{#t} if @var{obj} is a compiled procedure, or @code{#f}
161otherwise.
46d666d4
AW
162@end deffn
163
81fd3152
AW
164@deffn {Scheme Procedure} program-objcode program
165@deffnx {C Function} scm_program_objcode (program)
73643339
AW
166Returns the object code associated with this program. @xref{Bytecode
167and Objcode}, for more information.
46d666d4
AW
168@end deffn
169
170@deffn {Scheme Procedure} program-objects program
171@deffnx {C Function} scm_program_objects (program)
172Returns the ``object table'' associated with this program, as a
173vector. @xref{VM Programs}, for more information.
5a069042
AW
174@end deffn
175
46d666d4
AW
176@deffn {Scheme Procedure} program-module program
177@deffnx {C Function} scm_program_module (program)
81fd3152
AW
178Returns the module that was current when this program was created. Can
179return @code{#f} if the compiler could determine that this information
180was unnecessary.
46d666d4
AW
181@end deffn
182
f916cbc4
AW
183@deffn {Scheme Procedure} program-free-variables program
184@deffnx {C Function} scm_program_free_variables (program)
185Returns the set of free variables that this program captures in its
186closure, as a vector. If a closure is code with data, you can get the
187code from @code{program-objcode}, and the data via
188@code{program-free-variables}.
189
190Some of the values captured are actually in variable ``boxes''.
191@xref{Variables and the VM}, for more information.
46d666d4
AW
192
193Users must not modify the returned value unless they think they're
194really clever.
195@end deffn
196
46d666d4 197@deffn {Scheme Procedure} program-meta program
f916cbc4 198@deffnx {C Function} scm_program_meta (program)
46d666d4
AW
199Return the metadata thunk of @var{program}, or @code{#f} if it has no
200metadata.
201
202When called, a metadata thunk returns a list of the following form:
f916cbc4 203@code{(@var{bindings} @var{sources} @var{arities} . @var{properties})}. The format
46d666d4
AW
204of each of these elements is discussed below.
205@end deffn
206
5a069042 207@deffn {Scheme Procedure} program-bindings program
f916cbc4 208@deffnx {Scheme Procedure} make-binding name boxed? index start end
5a069042 209@deffnx {Scheme Procedure} binding:name binding
f916cbc4 210@deffnx {Scheme Procedure} binding:boxed? binding
5a069042
AW
211@deffnx {Scheme Procedure} binding:index binding
212@deffnx {Scheme Procedure} binding:start binding
213@deffnx {Scheme Procedure} binding:end binding
214Bindings annotations for programs, along with their accessors.
215
216Bindings declare names and liveness extents for block-local variables.
217The best way to see what these are is to play around with them at a
f916cbc4 218REPL. @xref{VM Concepts}, for more information.
5a069042 219
81fd3152
AW
220Note that bindings information is stored in a program as part of its
221metadata thunk, so including it in the generated object code does not
222impose a runtime performance penalty.
5a069042
AW
223@end deffn
224
225@deffn {Scheme Procedure} program-sources program
226@deffnx {Scheme Procedure} source:addr source
227@deffnx {Scheme Procedure} source:line source
228@deffnx {Scheme Procedure} source:column source
229@deffnx {Scheme Procedure} source:file source
230Source location annotations for programs, along with their accessors.
231
46d666d4
AW
232Source location information propagates through the compiler and ends
233up being serialized to the program's metadata. This information is
234keyed by the offset of the instruction pointer within the object code
235of the program. Specifically, it is keyed on the @code{ip} @emph{just
236following} an instruction, so that backtraces can find the source
237location of a call that is in progress.
5a069042
AW
238@end deffn
239
f916cbc4
AW
240@deffn {Scheme Procedure} program-arities program
241@deffnx {C Function} scm_program_arities (program)
242@deffnx {Scheme Procedure} program-arity program ip
243@deffnx {Scheme Procedure} arity:start arity
244@deffnx {Scheme Procedure} arity:end arity
245@deffnx {Scheme Procedure} arity:nreq arity
246@deffnx {Scheme Procedure} arity:nopt arity
247@deffnx {Scheme Procedure} arity:rest? arity
248@deffnx {Scheme Procedure} arity:kw arity
249@deffnx {Scheme Procedure} arity:allow-other-keys? arity
250Accessors for a representation of the ``arity'' of a program.
251
252The normal case is that a procedure has one arity. For example,
253@code{(lambda (x) x)}, takes one required argument, and that's it. One
254could access that number of required arguments via @code{(arity:nreq
255(program-arities (lambda (x) x)))}. Similarly, @code{arity:nopt} gets
256the number of optional arguments, and @code{arity:rest?} returns a true
257value if the procedure has a rest arg.
258
259@code{arity:kw} returns a list of @code{(@var{kw} . @var{idx})} pairs,
260if the procedure has keyword arguments. The @var{idx} refers to the
261@var{idx}th local variable; @xref{Variables and the VM}, for more
262information. Finally @code{arity:allow-other-keys?} returns a true
263value if other keys are allowed. @xref{Optional Arguments}, for more
264information.
265
266So what about @code{arity:start} and @code{arity:end}, then? They
267return the range of bytes in the program's bytecode for which a given
268arity is valid. You see, a procedure can actually have more than one
269arity. The question, ``what is a procedure's arity'' only really makes
270sense at certain points in the program, delimited by these
271@code{arity:start} and @code{arity:end} values.
272@end deffn
273
6fca8730 274@deffn {Scheme Procedure} program-arguments-alist program [ip]
9f17d967
AW
275Return an association list describing the arguments that @var{program} accepts, or
276@code{#f} if the information cannot be obtained.
277
4dbac5e0
AW
278The alist keys that are currently defined are `required', `optional',
279`keyword', `allow-other-keys?', and `rest'. For example:
280
9f17d967
AW
281@example
282(program-arguments-alist
283 (lambda* (a b #:optional c #:key (d 1) #:rest e)
284 #t)) @result{}
285((required . (a b))
286 (optional . (c))
287 (keyword . ((#:d . 4)))
288 (allow-other-keys? . #f)
289 (rest . d))
290@end example
4dbac5e0 291@end deffn
9f17d967 292
4dbac5e0
AW
293@deffn {Scheme Procedure} program-lambda-list program [ip]
294Return a representation of the arguments of @var{program} as a lambda
295list, or @code{#f} if this information is not available.
9f17d967 296
4dbac5e0 297For example:
6fca8730 298
4dbac5e0 299@example
84af582d 300(program-lambda-list
4dbac5e0
AW
301 (lambda* (a b #:optional c #:key (d 1) #:rest e)
302 #t)) @result{}
303@end example
6fca8730 304@end deffn
00ce5125 305
07d83abe
MV
306@node Optional Arguments
307@subsection Optional Arguments
308
07d83abe
MV
309Scheme procedures, as defined in R5RS, can either handle a fixed number
310of actual arguments, or a fixed number of actual arguments followed by
311arbitrarily many additional arguments. Writing procedures of variable
312arity can be useful, but unfortunately, the syntactic means for handling
313argument lists of varying length is a bit inconvenient. It is possible
f916cbc4 314to give names to the fixed number of arguments, but the remaining
07d83abe
MV
315(optional) arguments can be only referenced as a list of values
316(@pxref{Lambda}).
317
f916cbc4
AW
318For this reason, Guile provides an extension to @code{lambda},
319@code{lambda*}, which allows the user to define procedures with
320optional and keyword arguments. In addition, Guile's virtual machine
321has low-level support for optional and keyword argument dispatch.
322Calls to procedures with optional and keyword arguments can be made
323cheaply, without allocating a rest list.
07d83abe
MV
324
325@menu
f916cbc4
AW
326* lambda* and define*:: Creating advanced argument handling procedures.
327* ice-9 optargs:: (ice-9 optargs) provides some utilities.
07d83abe
MV
328@end menu
329
330
f916cbc4
AW
331@node lambda* and define*
332@subsubsection lambda* and define*.
07d83abe 333
f916cbc4
AW
334@code{lambda*} is like @code{lambda}, except with some extensions to
335allow optional and keyword arguments.
07d83abe 336
994d87be
BT
337@deffn {library syntax} lambda* ([var@dots{}] @* @
338 [#:optional vardef@dots{}] @* @
339 [#:key vardef@dots{} [#:allow-other-keys]] @* @
340 [#:rest var | . var]) @* @
341 body1 body2 @dots{}
edcd3e83
KR
342@sp 1
343Create a procedure which takes optional and/or keyword arguments
344specified with @code{#:optional} and @code{#:key}. For example,
07d83abe
MV
345
346@lisp
347(lambda* (a b #:optional c d . e) '())
348@end lisp
349
edcd3e83
KR
350is a procedure with fixed arguments @var{a} and @var{b}, optional
351arguments @var{c} and @var{d}, and rest argument @var{e}. If the
07d83abe
MV
352optional arguments are omitted in a call, the variables for them are
353bound to @code{#f}.
354
f916cbc4
AW
355@fnindex define*
356Likewise, @code{define*} is syntactic sugar for defining procedures
357using @code{lambda*}.
358
359@code{lambda*} can also make procedures with keyword arguments. For
360example, a procedure defined like this:
07d83abe
MV
361
362@lisp
f916cbc4
AW
363(define* (sir-yes-sir #:key action how-high)
364 (list action how-high))
07d83abe
MV
365@end lisp
366
f916cbc4
AW
367can be called as @code{(sir-yes-sir #:action 'jump)},
368@code{(sir-yes-sir #:how-high 13)}, @code{(sir-yes-sir #:action
369'lay-down #:how-high 0)}, or just @code{(sir-yes-sir)}. Whichever
370arguments are given as keywords are bound to values (and those not
371given are @code{#f}).
07d83abe 372
edcd3e83
KR
373Optional and keyword arguments can also have default values to take
374when not present in a call, by giving a two-element list of variable
375name and expression. For example in
07d83abe
MV
376
377@lisp
f916cbc4
AW
378(define* (frob foo #:optional (bar 42) #:key (baz 73))
379 (list foo bar baz))
07d83abe
MV
380@end lisp
381
382@var{foo} is a fixed argument, @var{bar} is an optional argument with
383default value 42, and baz is a keyword argument with default value 73.
edcd3e83
KR
384Default value expressions are not evaluated unless they are needed,
385and until the procedure is called.
07d83abe 386
edcd3e83
KR
387Normally it's an error if a call has keywords other than those
388specified by @code{#:key}, but adding @code{#:allow-other-keys} to the
389definition (after the keyword argument declarations) will ignore
390unknown keywords.
07d83abe 391
edcd3e83
KR
392If a call has a keyword given twice, the last value is used. For
393example,
07d83abe
MV
394
395@lisp
f916cbc4
AW
396(define* (flips #:key (heads 0) (tails 0))
397 (display (list heads tails)))
398
399(flips #:heads 37 #:tails 42 #:heads 99)
edcd3e83 400@print{} (99 42)
07d83abe
MV
401@end lisp
402
edcd3e83
KR
403@code{#:rest} is a synonym for the dotted syntax rest argument. The
404argument lists @code{(a . b)} and @code{(a #:rest b)} are equivalent
405in all respects. This is provided for more similarity to DSSSL,
406MIT-Scheme and Kawa among others, as well as for refugees from other
407Lisp dialects.
408
409When @code{#:key} is used together with a rest argument, the keyword
410parameters in a call all remain in the rest list. This is the same as
411Common Lisp. For example,
07d83abe 412
edcd3e83
KR
413@lisp
414((lambda* (#:key (x 0) #:allow-other-keys #:rest r)
415 (display r))
416 #:x 123 #:y 456)
417@print{} (#:x 123 #:y 456)
418@end lisp
419
420@code{#:optional} and @code{#:key} establish their bindings
f916cbc4
AW
421successively, from left to right. This means default expressions can
422refer back to prior parameters, for example
edcd3e83
KR
423
424@lisp
425(lambda* (start #:optional (end (+ 10 start)))
426 (do ((i start (1+ i)))
427 ((> i end))
428 (display i)))
429@end lisp
f916cbc4
AW
430
431The exception to this left-to-right scoping rule is the rest argument.
432If there is a rest argument, it is bound after the optional arguments,
433but before the keyword arguments.
07d83abe
MV
434@end deffn
435
436
f916cbc4
AW
437@node ice-9 optargs
438@subsubsection (ice-9 optargs)
07d83abe 439
f916cbc4
AW
440Before Guile 2.0, @code{lambda*} and @code{define*} were implemented
441using macros that processed rest list arguments. This was not optimal,
442as calling procedures with optional arguments had to allocate rest
443lists at every procedure invocation. Guile 2.0 improved this
444situation by bringing optional and keyword arguments into Guile's
445core.
07d83abe 446
f916cbc4
AW
447However there are occasions in which you have a list and want to parse
448it for optional or keyword arguments. Guile's @code{(ice-9 optargs)}
449provides some macros to help with that task.
07d83abe 450
f916cbc4
AW
451The syntax @code{let-optional} and @code{let-optional*} are for
452destructuring rest argument lists and giving names to the various list
453elements. @code{let-optional} binds all variables simultaneously, while
454@code{let-optional*} binds them sequentially, consistent with @code{let}
455and @code{let*} (@pxref{Local Bindings}).
456
df0a1002
BT
457@deffn {library syntax} let-optional rest-arg (binding @dots{}) body1 body2 @dots{}
458@deffnx {library syntax} let-optional* rest-arg (binding @dots{}) body1 body2 @dots{}
f916cbc4
AW
459These two macros give you an optional argument interface that is very
460@dfn{Schemey} and introduces no fancy syntax. They are compatible with
461the scsh macros of the same name, but are slightly extended. Each of
462@var{binding} may be of one of the forms @var{var} or @code{(@var{var}
463@var{default-value})}. @var{rest-arg} should be the rest-argument of the
464procedures these are used from. The items in @var{rest-arg} are
465sequentially bound to the variable names are given. When @var{rest-arg}
466runs out, the remaining vars are bound either to the default values or
467@code{#f} if no default value was specified. @var{rest-arg} remains
468bound to whatever may have been left of @var{rest-arg}.
07d83abe 469
df0a1002
BT
470After binding the variables, the expressions @var{body1} @var{body2} @dots{}
471are evaluated in order.
f916cbc4 472@end deffn
07d83abe 473
f916cbc4
AW
474Similarly, @code{let-keywords} and @code{let-keywords*} extract values
475from keyword style argument lists, binding local variables to those
476values or to defaults.
07d83abe 477
df0a1002
BT
478@deffn {library syntax} let-keywords args allow-other-keys? (binding @dots{}) body1 body2 @dots{}
479@deffnx {library syntax} let-keywords* args allow-other-keys? (binding @dots{}) body1 body2 @dots{}
f916cbc4
AW
480@var{args} is evaluated and should give a list of the form
481@code{(#:keyword1 value1 #:keyword2 value2 @dots{})}. The
df0a1002
BT
482@var{binding}s are variables and default expressions, with the variables
483to be set (by name) from the keyword values. The @var{body1}
484@var{body2} @dots{} forms are then evaluated and the last is the
485result. An example will make the syntax clearest,
f916cbc4
AW
486
487@example
488(define args '(#:xyzzy "hello" #:foo "world"))
07d83abe 489
f916cbc4
AW
490(let-keywords args #t
491 ((foo "default for foo")
492 (bar (string-append "default" "for" "bar")))
493 (display foo)
494 (display ", ")
495 (display bar))
496@print{} world, defaultforbar
497@end example
07d83abe 498
f916cbc4
AW
499The binding for @code{foo} comes from the @code{#:foo} keyword in
500@code{args}. But the binding for @code{bar} is the default in the
501@code{let-keywords}, since there's no @code{#:bar} in the args.
502
503@var{allow-other-keys?} is evaluated and controls whether unknown
504keywords are allowed in the @var{args} list. When true other keys are
505ignored (such as @code{#:xyzzy} in the example), when @code{#f} an
506error is thrown for anything unknown.
507@end deffn
508
509@code{(ice-9 optargs)} also provides some more @code{define*} sugar,
510which is not so useful with modern Guile coding, but still supported:
511@code{define*-public} is the @code{lambda*} version of
512@code{define-public}; @code{defmacro*} and @code{defmacro*-public}
513exist for defining macros with the improved argument list handling
514possibilities. The @code{-public} versions not only define the
515procedures/macros, but also export them from the current module.
516
df0a1002 517@deffn {library syntax} define*-public formals body1 body2 @dots{}
f916cbc4 518Like a mix of @code{define*} and @code{define-public}.
07d83abe
MV
519@end deffn
520
df0a1002
BT
521@deffn {library syntax} defmacro* name formals body1 body2 @dots{}
522@deffnx {library syntax} defmacro*-public name formals body1 body2 @dots{}
07d83abe
MV
523These are just like @code{defmacro} and @code{defmacro-public} except that they
524take @code{lambda*}-style extended parameter lists, where @code{#:optional},
525@code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
526semantics. Here is an example of a macro with an optional argument:
527
528@lisp
ecb87335 529(defmacro* transmogrify (a #:optional b)
f916cbc4 530 (a 1))
07d83abe
MV
531@end lisp
532@end deffn
533
f916cbc4
AW
534@node Case-lambda
535@subsection Case-lambda
536@cindex SRFI-16
537@cindex variable arity
538@cindex arity, variable
539
540R5RS's rest arguments are indeed useful and very general, but they
541often aren't the most appropriate or efficient means to get the job
542done. For example, @code{lambda*} is a much better solution to the
543optional argument problem than @code{lambda} with rest arguments.
544
545@fnindex case-lambda
546Likewise, @code{case-lambda} works well for when you want one
547procedure to do double duty (or triple, or ...), without the penalty
548of consing a rest list.
549
550For example:
551
552@lisp
553(define (make-accum n)
554 (case-lambda
555 (() n)
556 ((m) (set! n (+ n m)) n)))
557
558(define a (make-accum 20))
559(a) @result{} 20
560(a 10) @result{} 30
561(a) @result{} 30
562@end lisp
563
564The value returned by a @code{case-lambda} form is a procedure which
565matches the number of actual arguments against the formals in the
566various clauses, in order. The first matching clause is selected, the
567corresponding values from the actual parameter list are bound to the
568variable names in the clauses and the body of the clause is evaluated.
569If no clause matches, an error is signalled.
570
571The syntax of the @code{case-lambda} form is defined in the following
572EBNF grammar. @dfn{Formals} means a formal argument list just like
573with @code{lambda} (@pxref{Lambda}).
574
575@example
576@group
577<case-lambda>
0426b3f8
MW
578 --> (case-lambda <case-lambda-clause>*)
579 --> (case-lambda <docstring> <case-lambda-clause>*)
f916cbc4
AW
580<case-lambda-clause>
581 --> (<formals> <definition-or-command>*)
582<formals>
583 --> (<identifier>*)
584 | (<identifier>* . <identifier>)
585 | <identifier>
586@end group
587@end example
588
589Rest lists can be useful with @code{case-lambda}:
590
591@lisp
592(define plus
593 (case-lambda
0426b3f8 594 "Return the sum of all arguments."
f916cbc4
AW
595 (() 0)
596 ((a) a)
597 ((a b) (+ a b))
598 ((a b . rest) (apply plus (+ a b) rest))))
599(plus 1 2 3) @result{} 6
600@end lisp
601
602@fnindex case-lambda*
603Also, for completeness. Guile defines @code{case-lambda*} as well,
604which is like @code{case-lambda}, except with @code{lambda*} clauses.
605A @code{case-lambda*} clause matches if the arguments fill the
606required arguments, but are not too many for the optional and/or rest
607arguments.
608
581f410f
AW
609Keyword arguments are possible with @code{case-lambda*} as well, but
610they do not contribute to the ``matching'' behavior, and their
611interactions with required, optional, and rest arguments can be
612surprising.
613
614For the purposes of @code{case-lambda*} (and of @code{case-lambda}, as a
615special case), a clause @dfn{matches} if it has enough required
616arguments, and not too many positional arguments. The required
617arguments are any arguments before the @code{#:optional}, @code{#:key},
618and @code{#:rest} arguments. @dfn{Positional} arguments are the
619required arguments, together with the optional arguments.
620
621In the absence of @code{#:key} or @code{#:rest} arguments, it's easy to
622see how there could be too many positional arguments: you pass 5
623arguments to a function that only takes 4 arguments, including optional
624arguments. If there is a @code{#:rest} argument, there can never be too
625many positional arguments: any application with enough required
626arguments for a clause will match that clause, even if there are also
627@code{#:key} arguments.
628
629Otherwise, for applications to a clause with @code{#:key} arguments (and
630without a @code{#:rest} argument), a clause will match there only if
631there are enough required arguments and if the next argument after
632binding required and optional arguments, if any, is a keyword. For
633efficiency reasons, Guile is currently unable to include keyword
634arguments in the matching algorithm. Clauses match on positional
635arguments only, not by comparing a given keyword to the available set of
636keyword arguments that a function has.
637
638Some examples follow.
639
640@example
641(define f
642 (case-lambda*
643 ((a #:optional b) 'clause-1)
644 ((a #:optional b #:key c) 'clause-2)
645 ((a #:key d) 'clause-3)
646 ((#:key e #:rest f) 'clause-4)))
647
648(f) @result{} clause-4
649(f 1) @result{} clause-1
650(f) @result{} clause-4
651(f #:e 10) clause-1
652(f 1 #:foo) clause-1
653(f 1 #:c 2) clause-2
654(f #:a #:b #:c #:d #:e) clause-4
655
656;; clause-2 will match anything that clause-3 would match.
657(f 1 #:d 2) @result{} error: bad keyword args in clause 2
658@end example
659
660Don't forget that the clauses are matched in order, and the first
661matching clause will be taken. This can result in a keyword being bound
662to a required argument, as in the case of @code{f #:e 10}.
663
07d83abe 664
18f06db9
LC
665@node Higher-Order Functions
666@subsection Higher-Order Functions
667
668@cindex higher-order functions
669
670As a functional programming language, Scheme allows the definition of
671@dfn{higher-order functions}, i.e., functions that take functions as
672arguments and/or return functions. Utilities to derive procedures from
673other procedures are provided and described below.
674
675@deffn {Scheme Procedure} const value
676Return a procedure that accepts any number of arguments and returns
677@var{value}.
678
679@lisp
680(procedure? (const 3)) @result{} #t
681((const 'hello)) @result{} hello
682((const 'hello) 'world) @result{} hello
683@end lisp
684@end deffn
685
686@deffn {Scheme Procedure} negate proc
687Return a procedure with the same arity as @var{proc} that returns the
688@code{not} of @var{proc}'s result.
689
690@lisp
691(procedure? (negate number?)) @result{} #t
692((negate odd?) 2) @result{} #t
693((negate real?) 'dream) @result{} #t
694((negate string-prefix?) "GNU" "GNU Guile")
695 @result{} #f
696(filter (negate number?) '(a 2 "b"))
697 @result{} (a "b")
698@end lisp
699@end deffn
700
df0a1002
BT
701@deffn {Scheme Procedure} compose proc1 proc2 @dots{}
702Compose @var{proc1} with the procedures @var{proc2} @dots{} such that
703the last @var{proc} argument is applied first and @var{proc1} last, and
704return the resulting procedure. The given procedures must have
705compatible arity.
18f06db9
LC
706
707@lisp
708(procedure? (compose 1+ 1-)) @result{} #t
709((compose sqrt 1+ 1+) 2) @result{} 2.0
710((compose 1+ sqrt) 3) @result{} 2.73205080756888
711(eq? (compose 1+) 1+) @result{} #t
712
713((compose zip unzip2) '((1 2) (a b)))
714 @result{} ((1 2) (a b))
715@end lisp
716@end deffn
717
718@deffn {Scheme Procedure} identity x
719Return X.
720@end deffn
721
8cd109bf
LC
722@deffn {Scheme Procedure} and=> value proc
723When @var{value} is @code{#f}, return @code{#f}. Otherwise, return
724@code{(@var{proc} @var{value})}.
725@end deffn
726
07d83abe
MV
727@node Procedure Properties
728@subsection Procedure Properties and Meta-information
729
f916cbc4
AW
730In addition to the information that is strictly necessary to run,
731procedures may have other associated information. For example, the
732name of a procedure is information not for the procedure, but about
733the procedure. This meta-information can be accessed via the procedure
734properties interface.
07d83abe 735
f916cbc4
AW
736The first group of procedures in this meta-interface are predicates to
737test whether a Scheme object is a procedure, or a special procedure,
bd5dea48
LC
738respectively. @code{procedure?} is the most general predicates, it
739returns @code{#t} for any kind of procedure.
07d83abe
MV
740
741@rnindex procedure?
742@deffn {Scheme Procedure} procedure? obj
743@deffnx {C Function} scm_procedure_p (obj)
744Return @code{#t} if @var{obj} is a procedure.
745@end deffn
746
07d83abe
MV
747@deffn {Scheme Procedure} thunk? obj
748@deffnx {C Function} scm_thunk_p (obj)
bd5dea48
LC
749Return @code{#t} if @var{obj} is a thunk---a procedure that does
750not accept arguments.
07d83abe
MV
751@end deffn
752
07d83abe 753@cindex procedure properties
f916cbc4
AW
754Procedure properties are general properties associated with
755procedures. These can be the name of a procedure or other relevant
07d83abe
MV
756information, such as debug hints.
757
758@deffn {Scheme Procedure} procedure-name proc
759@deffnx {C Function} scm_procedure_name (proc)
760Return the name of the procedure @var{proc}
761@end deffn
762
763@deffn {Scheme Procedure} procedure-source proc
764@deffnx {C Function} scm_procedure_source (proc)
f916cbc4
AW
765Return the source of the procedure @var{proc}. Returns @code{#f} if
766the source code is not available.
07d83abe
MV
767@end deffn
768
07d83abe
MV
769@deffn {Scheme Procedure} procedure-properties proc
770@deffnx {C Function} scm_procedure_properties (proc)
f916cbc4
AW
771Return the properties associated with @var{proc}, as an association
772list.
07d83abe
MV
773@end deffn
774
f916cbc4
AW
775@deffn {Scheme Procedure} procedure-property proc key
776@deffnx {C Function} scm_procedure_property (proc, key)
777Return the property of @var{proc} with name @var{key}.
07d83abe
MV
778@end deffn
779
780@deffn {Scheme Procedure} set-procedure-properties! proc alist
781@deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
f916cbc4 782Set @var{proc}'s property list to @var{alist}.
07d83abe
MV
783@end deffn
784
f916cbc4
AW
785@deffn {Scheme Procedure} set-procedure-property! proc key value
786@deffnx {C Function} scm_set_procedure_property_x (proc, key, value)
787In @var{proc}'s property list, set the property named @var{key} to
07d83abe
MV
788@var{value}.
789@end deffn
790
791@cindex procedure documentation
792Documentation for a procedure can be accessed with the procedure
793@code{procedure-documentation}.
794
795@deffn {Scheme Procedure} procedure-documentation proc
796@deffnx {C Function} scm_procedure_documentation (proc)
797Return the documentation string associated with @code{proc}. By
798convention, if a procedure contains more than one expression and the
799first expression is a string constant, that string is assumed to contain
800documentation for that procedure.
801@end deffn
802
07d83abe
MV
803
804@node Procedures with Setters
805@subsection Procedures with Setters
806
807@c FIXME::martin: Review me!
808
809@c FIXME::martin: Document `operator struct'.
810
811@cindex procedure with setter
812@cindex setter
813A @dfn{procedure with setter} is a special kind of procedure which
814normally behaves like any accessor procedure, that is a procedure which
815accesses a data structure. The difference is that this kind of
816procedure has a so-called @dfn{setter} attached, which is a procedure
817for storing something into a data structure.
818
819Procedures with setters are treated specially when the procedure appears
820in the special form @code{set!} (REFFIXME). How it works is best shown
821by example.
822
823Suppose we have a procedure called @code{foo-ref}, which accepts two
824arguments, a value of type @code{foo} and an integer. The procedure
825returns the value stored at the given index in the @code{foo} object.
826Let @code{f} be a variable containing such a @code{foo} data
827structure.@footnote{Working definitions would be:
828@lisp
829(define foo-ref vector-ref)
830(define foo-set! vector-set!)
831(define f (make-vector 2 #f))
832@end lisp
833}
834
835@lisp
836(foo-ref f 0) @result{} bar
837(foo-ref f 1) @result{} braz
838@end lisp
839
840Also suppose that a corresponding setter procedure called
841@code{foo-set!} does exist.
842
843@lisp
844(foo-set! f 0 'bla)
845(foo-ref f 0) @result{} bla
846@end lisp
847
848Now we could create a new procedure called @code{foo}, which is a
849procedure with setter, by calling @code{make-procedure-with-setter} with
850the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
851Let us call this new procedure @code{foo}.
852
853@lisp
854(define foo (make-procedure-with-setter foo-ref foo-set!))
855@end lisp
856
857@code{foo} can from now an be used to either read from the data
858structure stored in @code{f}, or to write into the structure.
859
860@lisp
861(set! (foo f 0) 'dum)
862(foo f 0) @result{} dum
863@end lisp
864
865@deffn {Scheme Procedure} make-procedure-with-setter procedure setter
866@deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
867Create a new procedure which behaves like @var{procedure}, but
868with the associated setter @var{setter}.
869@end deffn
870
871@deffn {Scheme Procedure} procedure-with-setter? obj
872@deffnx {C Function} scm_procedure_with_setter_p (obj)
873Return @code{#t} if @var{obj} is a procedure with an
874associated setter procedure.
875@end deffn
876
877@deffn {Scheme Procedure} procedure proc
878@deffnx {C Function} scm_procedure (proc)
3323ec06
NJ
879Return the procedure of @var{proc}, which must be an
880applicable struct.
07d83abe
MV
881@end deffn
882
883@deffn {Scheme Procedure} setter proc
884Return the setter of @var{proc}, which must be either a procedure with
885setter or an operator struct.
886@end deffn
887
165b10dd
AR
888@node Inlinable Procedures
889@subsection Inlinable Procedures
890
43e53d64
LC
891@cindex inlining
892@cindex procedure inlining
165b10dd
AR
893You can define an @dfn{inlinable procedure} by using
894@code{define-inlinable} instead of @code{define}. An inlinable
895procedure behaves the same as a regular procedure, but direct calls will
896result in the procedure body being inlined into the caller.
897
43e53d64
LC
898@cindex partial evaluator
899Bear in mind that starting from version 2.0.3, Guile has a partial
900evaluator that can inline the body of inner procedures when deemed
901appropriate:
902
903@example
904scheme@@(guile-user)> ,optimize (define (foo x)
905 (define (bar) (+ x 3))
906 (* (bar) 2))
907$1 = (define foo
908 (lambda (#@{x 94@}#) (* (+ #@{x 94@}# 3) 2)))
909@end example
910
911@noindent
912The partial evaluator does not inline top-level bindings, though, so
913this is a situation where you may find it interesting to use
914@code{define-inlinable}.
915
165b10dd
AR
916Procedures defined with @code{define-inlinable} are @emph{always}
917inlined, at all direct call sites. This eliminates function call
918overhead at the expense of an increase in code size. Additionally, the
919caller will not transparently use the new definition if the inline
920procedure is redefined. It is not possible to trace an inlined
921procedures or install a breakpoint in it (@pxref{Traps}). For these
922reasons, you should not make a procedure inlinable unless it
923demonstrably improves performance in a crucial way.
924
925In general, only small procedures should be considered for inlining, as
926making large procedures inlinable will probably result in an increase in
927code size. Additionally, the elimination of the call overhead rarely
b3da54d1 928matters for large procedures.
165b10dd 929
df0a1002 930@deffn {Scheme Syntax} define-inlinable (name parameter @dots{}) body1 body2 @dots{}
165b10dd 931Define @var{name} as a procedure with parameters @var{parameter}s and
df0a1002 932bodies @var{body1}, @var{body2}, @enddots{}.
165b10dd 933@end deffn
07d83abe 934
07d83abe
MV
935@c Local Variables:
936@c TeX-master: "guile.texi"
937@c End: