Docstrings in (ice-9 iconv)
[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)
160Returns @code{#t} iff @var{obj} is a compiled procedure.
161@end deffn
162
81fd3152
AW
163@deffn {Scheme Procedure} program-objcode program
164@deffnx {C Function} scm_program_objcode (program)
73643339
AW
165Returns the object code associated with this program. @xref{Bytecode
166and Objcode}, for more information.
46d666d4
AW
167@end deffn
168
169@deffn {Scheme Procedure} program-objects program
170@deffnx {C Function} scm_program_objects (program)
171Returns the ``object table'' associated with this program, as a
172vector. @xref{VM Programs}, for more information.
5a069042
AW
173@end deffn
174
46d666d4
AW
175@deffn {Scheme Procedure} program-module program
176@deffnx {C Function} scm_program_module (program)
81fd3152
AW
177Returns the module that was current when this program was created. Can
178return @code{#f} if the compiler could determine that this information
179was unnecessary.
46d666d4
AW
180@end deffn
181
f916cbc4
AW
182@deffn {Scheme Procedure} program-free-variables program
183@deffnx {C Function} scm_program_free_variables (program)
184Returns the set of free variables that this program captures in its
185closure, as a vector. If a closure is code with data, you can get the
186code from @code{program-objcode}, and the data via
187@code{program-free-variables}.
188
189Some of the values captured are actually in variable ``boxes''.
190@xref{Variables and the VM}, for more information.
46d666d4
AW
191
192Users must not modify the returned value unless they think they're
193really clever.
194@end deffn
195
46d666d4 196@deffn {Scheme Procedure} program-meta program
f916cbc4 197@deffnx {C Function} scm_program_meta (program)
46d666d4
AW
198Return the metadata thunk of @var{program}, or @code{#f} if it has no
199metadata.
200
201When called, a metadata thunk returns a list of the following form:
f916cbc4 202@code{(@var{bindings} @var{sources} @var{arities} . @var{properties})}. The format
46d666d4
AW
203of each of these elements is discussed below.
204@end deffn
205
5a069042 206@deffn {Scheme Procedure} program-bindings program
f916cbc4 207@deffnx {Scheme Procedure} make-binding name boxed? index start end
5a069042 208@deffnx {Scheme Procedure} binding:name binding
f916cbc4 209@deffnx {Scheme Procedure} binding:boxed? binding
5a069042
AW
210@deffnx {Scheme Procedure} binding:index binding
211@deffnx {Scheme Procedure} binding:start binding
212@deffnx {Scheme Procedure} binding:end binding
213Bindings annotations for programs, along with their accessors.
214
215Bindings declare names and liveness extents for block-local variables.
216The best way to see what these are is to play around with them at a
f916cbc4 217REPL. @xref{VM Concepts}, for more information.
5a069042 218
81fd3152
AW
219Note that bindings information is stored in a program as part of its
220metadata thunk, so including it in the generated object code does not
221impose a runtime performance penalty.
5a069042
AW
222@end deffn
223
224@deffn {Scheme Procedure} program-sources program
225@deffnx {Scheme Procedure} source:addr source
226@deffnx {Scheme Procedure} source:line source
227@deffnx {Scheme Procedure} source:column source
228@deffnx {Scheme Procedure} source:file source
229Source location annotations for programs, along with their accessors.
230
46d666d4
AW
231Source location information propagates through the compiler and ends
232up being serialized to the program's metadata. This information is
233keyed by the offset of the instruction pointer within the object code
234of the program. Specifically, it is keyed on the @code{ip} @emph{just
235following} an instruction, so that backtraces can find the source
236location of a call that is in progress.
5a069042
AW
237@end deffn
238
f916cbc4
AW
239@deffn {Scheme Procedure} program-arities program
240@deffnx {C Function} scm_program_arities (program)
241@deffnx {Scheme Procedure} program-arity program ip
242@deffnx {Scheme Procedure} arity:start arity
243@deffnx {Scheme Procedure} arity:end arity
244@deffnx {Scheme Procedure} arity:nreq arity
245@deffnx {Scheme Procedure} arity:nopt arity
246@deffnx {Scheme Procedure} arity:rest? arity
247@deffnx {Scheme Procedure} arity:kw arity
248@deffnx {Scheme Procedure} arity:allow-other-keys? arity
249Accessors for a representation of the ``arity'' of a program.
250
251The normal case is that a procedure has one arity. For example,
252@code{(lambda (x) x)}, takes one required argument, and that's it. One
253could access that number of required arguments via @code{(arity:nreq
254(program-arities (lambda (x) x)))}. Similarly, @code{arity:nopt} gets
255the number of optional arguments, and @code{arity:rest?} returns a true
256value if the procedure has a rest arg.
257
258@code{arity:kw} returns a list of @code{(@var{kw} . @var{idx})} pairs,
259if the procedure has keyword arguments. The @var{idx} refers to the
260@var{idx}th local variable; @xref{Variables and the VM}, for more
261information. Finally @code{arity:allow-other-keys?} returns a true
262value if other keys are allowed. @xref{Optional Arguments}, for more
263information.
264
265So what about @code{arity:start} and @code{arity:end}, then? They
266return the range of bytes in the program's bytecode for which a given
267arity is valid. You see, a procedure can actually have more than one
268arity. The question, ``what is a procedure's arity'' only really makes
269sense at certain points in the program, delimited by these
270@code{arity:start} and @code{arity:end} values.
271@end deffn
272
6fca8730 273@deffn {Scheme Procedure} program-arguments-alist program [ip]
9f17d967
AW
274Return an association list describing the arguments that @var{program} accepts, or
275@code{#f} if the information cannot be obtained.
276
4dbac5e0
AW
277The alist keys that are currently defined are `required', `optional',
278`keyword', `allow-other-keys?', and `rest'. For example:
279
9f17d967
AW
280@example
281(program-arguments-alist
282 (lambda* (a b #:optional c #:key (d 1) #:rest e)
283 #t)) @result{}
284((required . (a b))
285 (optional . (c))
286 (keyword . ((#:d . 4)))
287 (allow-other-keys? . #f)
288 (rest . d))
289@end example
4dbac5e0 290@end deffn
9f17d967 291
4dbac5e0
AW
292@deffn {Scheme Procedure} program-lambda-list program [ip]
293Return a representation of the arguments of @var{program} as a lambda
294list, or @code{#f} if this information is not available.
9f17d967 295
4dbac5e0 296For example:
6fca8730 297
4dbac5e0
AW
298@example
299(program-lambda-alist
300 (lambda* (a b #:optional c #:key (d 1) #:rest e)
301 #t)) @result{}
302@end example
6fca8730 303@end deffn
00ce5125 304
07d83abe
MV
305@node Optional Arguments
306@subsection Optional Arguments
307
07d83abe
MV
308Scheme procedures, as defined in R5RS, can either handle a fixed number
309of actual arguments, or a fixed number of actual arguments followed by
310arbitrarily many additional arguments. Writing procedures of variable
311arity can be useful, but unfortunately, the syntactic means for handling
312argument lists of varying length is a bit inconvenient. It is possible
f916cbc4 313to give names to the fixed number of arguments, but the remaining
07d83abe
MV
314(optional) arguments can be only referenced as a list of values
315(@pxref{Lambda}).
316
f916cbc4
AW
317For this reason, Guile provides an extension to @code{lambda},
318@code{lambda*}, which allows the user to define procedures with
319optional and keyword arguments. In addition, Guile's virtual machine
320has low-level support for optional and keyword argument dispatch.
321Calls to procedures with optional and keyword arguments can be made
322cheaply, without allocating a rest list.
07d83abe
MV
323
324@menu
f916cbc4
AW
325* lambda* and define*:: Creating advanced argument handling procedures.
326* ice-9 optargs:: (ice-9 optargs) provides some utilities.
07d83abe
MV
327@end menu
328
329
f916cbc4
AW
330@node lambda* and define*
331@subsubsection lambda* and define*.
07d83abe 332
f916cbc4
AW
333@code{lambda*} is like @code{lambda}, except with some extensions to
334allow optional and keyword arguments.
07d83abe 335
edcd3e83
KR
336@deffn {library syntax} lambda* ([var@dots{}] @* [#:optional vardef@dots{}] @* [#:key vardef@dots{} [#:allow-other-keys]] @* [#:rest var | . var]) @* body
337@sp 1
338Create a procedure which takes optional and/or keyword arguments
339specified with @code{#:optional} and @code{#:key}. For example,
07d83abe
MV
340
341@lisp
342(lambda* (a b #:optional c d . e) '())
343@end lisp
344
edcd3e83
KR
345is a procedure with fixed arguments @var{a} and @var{b}, optional
346arguments @var{c} and @var{d}, and rest argument @var{e}. If the
07d83abe
MV
347optional arguments are omitted in a call, the variables for them are
348bound to @code{#f}.
349
f916cbc4
AW
350@fnindex define*
351Likewise, @code{define*} is syntactic sugar for defining procedures
352using @code{lambda*}.
353
354@code{lambda*} can also make procedures with keyword arguments. For
355example, a procedure defined like this:
07d83abe
MV
356
357@lisp
f916cbc4
AW
358(define* (sir-yes-sir #:key action how-high)
359 (list action how-high))
07d83abe
MV
360@end lisp
361
f916cbc4
AW
362can be called as @code{(sir-yes-sir #:action 'jump)},
363@code{(sir-yes-sir #:how-high 13)}, @code{(sir-yes-sir #:action
364'lay-down #:how-high 0)}, or just @code{(sir-yes-sir)}. Whichever
365arguments are given as keywords are bound to values (and those not
366given are @code{#f}).
07d83abe 367
edcd3e83
KR
368Optional and keyword arguments can also have default values to take
369when not present in a call, by giving a two-element list of variable
370name and expression. For example in
07d83abe
MV
371
372@lisp
f916cbc4
AW
373(define* (frob foo #:optional (bar 42) #:key (baz 73))
374 (list foo bar baz))
07d83abe
MV
375@end lisp
376
377@var{foo} is a fixed argument, @var{bar} is an optional argument with
378default value 42, and baz is a keyword argument with default value 73.
edcd3e83
KR
379Default value expressions are not evaluated unless they are needed,
380and until the procedure is called.
07d83abe 381
edcd3e83
KR
382Normally it's an error if a call has keywords other than those
383specified by @code{#:key}, but adding @code{#:allow-other-keys} to the
384definition (after the keyword argument declarations) will ignore
385unknown keywords.
07d83abe 386
edcd3e83
KR
387If a call has a keyword given twice, the last value is used. For
388example,
07d83abe
MV
389
390@lisp
f916cbc4
AW
391(define* (flips #:key (heads 0) (tails 0))
392 (display (list heads tails)))
393
394(flips #:heads 37 #:tails 42 #:heads 99)
edcd3e83 395@print{} (99 42)
07d83abe
MV
396@end lisp
397
edcd3e83
KR
398@code{#:rest} is a synonym for the dotted syntax rest argument. The
399argument lists @code{(a . b)} and @code{(a #:rest b)} are equivalent
400in all respects. This is provided for more similarity to DSSSL,
401MIT-Scheme and Kawa among others, as well as for refugees from other
402Lisp dialects.
403
404When @code{#:key} is used together with a rest argument, the keyword
405parameters in a call all remain in the rest list. This is the same as
406Common Lisp. For example,
07d83abe 407
edcd3e83
KR
408@lisp
409((lambda* (#:key (x 0) #:allow-other-keys #:rest r)
410 (display r))
411 #:x 123 #:y 456)
412@print{} (#:x 123 #:y 456)
413@end lisp
414
415@code{#:optional} and @code{#:key} establish their bindings
f916cbc4
AW
416successively, from left to right. This means default expressions can
417refer back to prior parameters, for example
edcd3e83
KR
418
419@lisp
420(lambda* (start #:optional (end (+ 10 start)))
421 (do ((i start (1+ i)))
422 ((> i end))
423 (display i)))
424@end lisp
f916cbc4
AW
425
426The exception to this left-to-right scoping rule is the rest argument.
427If there is a rest argument, it is bound after the optional arguments,
428but before the keyword arguments.
07d83abe
MV
429@end deffn
430
431
f916cbc4
AW
432@node ice-9 optargs
433@subsubsection (ice-9 optargs)
07d83abe 434
f916cbc4
AW
435Before Guile 2.0, @code{lambda*} and @code{define*} were implemented
436using macros that processed rest list arguments. This was not optimal,
437as calling procedures with optional arguments had to allocate rest
438lists at every procedure invocation. Guile 2.0 improved this
439situation by bringing optional and keyword arguments into Guile's
440core.
07d83abe 441
f916cbc4
AW
442However there are occasions in which you have a list and want to parse
443it for optional or keyword arguments. Guile's @code{(ice-9 optargs)}
444provides some macros to help with that task.
07d83abe 445
f916cbc4
AW
446The syntax @code{let-optional} and @code{let-optional*} are for
447destructuring rest argument lists and giving names to the various list
448elements. @code{let-optional} binds all variables simultaneously, while
449@code{let-optional*} binds them sequentially, consistent with @code{let}
450and @code{let*} (@pxref{Local Bindings}).
451
df0a1002
BT
452@deffn {library syntax} let-optional rest-arg (binding @dots{}) body1 body2 @dots{}
453@deffnx {library syntax} let-optional* rest-arg (binding @dots{}) body1 body2 @dots{}
f916cbc4
AW
454These two macros give you an optional argument interface that is very
455@dfn{Schemey} and introduces no fancy syntax. They are compatible with
456the scsh macros of the same name, but are slightly extended. Each of
457@var{binding} may be of one of the forms @var{var} or @code{(@var{var}
458@var{default-value})}. @var{rest-arg} should be the rest-argument of the
459procedures these are used from. The items in @var{rest-arg} are
460sequentially bound to the variable names are given. When @var{rest-arg}
461runs out, the remaining vars are bound either to the default values or
462@code{#f} if no default value was specified. @var{rest-arg} remains
463bound to whatever may have been left of @var{rest-arg}.
07d83abe 464
df0a1002
BT
465After binding the variables, the expressions @var{body1} @var{body2} @dots{}
466are evaluated in order.
f916cbc4 467@end deffn
07d83abe 468
f916cbc4
AW
469Similarly, @code{let-keywords} and @code{let-keywords*} extract values
470from keyword style argument lists, binding local variables to those
471values or to defaults.
07d83abe 472
df0a1002
BT
473@deffn {library syntax} let-keywords args allow-other-keys? (binding @dots{}) body1 body2 @dots{}
474@deffnx {library syntax} let-keywords* args allow-other-keys? (binding @dots{}) body1 body2 @dots{}
f916cbc4
AW
475@var{args} is evaluated and should give a list of the form
476@code{(#:keyword1 value1 #:keyword2 value2 @dots{})}. The
df0a1002
BT
477@var{binding}s are variables and default expressions, with the variables
478to be set (by name) from the keyword values. The @var{body1}
479@var{body2} @dots{} forms are then evaluated and the last is the
480result. An example will make the syntax clearest,
f916cbc4
AW
481
482@example
483(define args '(#:xyzzy "hello" #:foo "world"))
07d83abe 484
f916cbc4
AW
485(let-keywords args #t
486 ((foo "default for foo")
487 (bar (string-append "default" "for" "bar")))
488 (display foo)
489 (display ", ")
490 (display bar))
491@print{} world, defaultforbar
492@end example
07d83abe 493
f916cbc4
AW
494The binding for @code{foo} comes from the @code{#:foo} keyword in
495@code{args}. But the binding for @code{bar} is the default in the
496@code{let-keywords}, since there's no @code{#:bar} in the args.
497
498@var{allow-other-keys?} is evaluated and controls whether unknown
499keywords are allowed in the @var{args} list. When true other keys are
500ignored (such as @code{#:xyzzy} in the example), when @code{#f} an
501error is thrown for anything unknown.
502@end deffn
503
504@code{(ice-9 optargs)} also provides some more @code{define*} sugar,
505which is not so useful with modern Guile coding, but still supported:
506@code{define*-public} is the @code{lambda*} version of
507@code{define-public}; @code{defmacro*} and @code{defmacro*-public}
508exist for defining macros with the improved argument list handling
509possibilities. The @code{-public} versions not only define the
510procedures/macros, but also export them from the current module.
511
df0a1002 512@deffn {library syntax} define*-public formals body1 body2 @dots{}
f916cbc4 513Like a mix of @code{define*} and @code{define-public}.
07d83abe
MV
514@end deffn
515
df0a1002
BT
516@deffn {library syntax} defmacro* name formals body1 body2 @dots{}
517@deffnx {library syntax} defmacro*-public name formals body1 body2 @dots{}
07d83abe
MV
518These are just like @code{defmacro} and @code{defmacro-public} except that they
519take @code{lambda*}-style extended parameter lists, where @code{#:optional},
520@code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
521semantics. Here is an example of a macro with an optional argument:
522
523@lisp
ecb87335 524(defmacro* transmogrify (a #:optional b)
f916cbc4 525 (a 1))
07d83abe
MV
526@end lisp
527@end deffn
528
f916cbc4
AW
529@node Case-lambda
530@subsection Case-lambda
531@cindex SRFI-16
532@cindex variable arity
533@cindex arity, variable
534
535R5RS's rest arguments are indeed useful and very general, but they
536often aren't the most appropriate or efficient means to get the job
537done. For example, @code{lambda*} is a much better solution to the
538optional argument problem than @code{lambda} with rest arguments.
539
540@fnindex case-lambda
541Likewise, @code{case-lambda} works well for when you want one
542procedure to do double duty (or triple, or ...), without the penalty
543of consing a rest list.
544
545For example:
546
547@lisp
548(define (make-accum n)
549 (case-lambda
550 (() n)
551 ((m) (set! n (+ n m)) n)))
552
553(define a (make-accum 20))
554(a) @result{} 20
555(a 10) @result{} 30
556(a) @result{} 30
557@end lisp
558
559The value returned by a @code{case-lambda} form is a procedure which
560matches the number of actual arguments against the formals in the
561various clauses, in order. The first matching clause is selected, the
562corresponding values from the actual parameter list are bound to the
563variable names in the clauses and the body of the clause is evaluated.
564If no clause matches, an error is signalled.
565
566The syntax of the @code{case-lambda} form is defined in the following
567EBNF grammar. @dfn{Formals} means a formal argument list just like
568with @code{lambda} (@pxref{Lambda}).
569
570@example
571@group
572<case-lambda>
573 --> (case-lambda <case-lambda-clause>)
574<case-lambda-clause>
575 --> (<formals> <definition-or-command>*)
576<formals>
577 --> (<identifier>*)
578 | (<identifier>* . <identifier>)
579 | <identifier>
580@end group
581@end example
582
583Rest lists can be useful with @code{case-lambda}:
584
585@lisp
586(define plus
587 (case-lambda
588 (() 0)
589 ((a) a)
590 ((a b) (+ a b))
591 ((a b . rest) (apply plus (+ a b) rest))))
592(plus 1 2 3) @result{} 6
593@end lisp
594
595@fnindex case-lambda*
596Also, for completeness. Guile defines @code{case-lambda*} as well,
597which is like @code{case-lambda}, except with @code{lambda*} clauses.
598A @code{case-lambda*} clause matches if the arguments fill the
599required arguments, but are not too many for the optional and/or rest
600arguments.
601
f916cbc4
AW
602Keyword arguments are possible with @code{case-lambda*}, but they do
603not contribute to the ``matching'' behavior. That is to say,
604@code{case-lambda*} matches only on required, optional, and rest
605arguments, and on the predicate; keyword arguments may be present but
606do not contribute to the ``success'' of a match. In fact a bad keyword
607argument list may cause an error to be raised.
07d83abe 608
18f06db9
LC
609@node Higher-Order Functions
610@subsection Higher-Order Functions
611
612@cindex higher-order functions
613
614As a functional programming language, Scheme allows the definition of
615@dfn{higher-order functions}, i.e., functions that take functions as
616arguments and/or return functions. Utilities to derive procedures from
617other procedures are provided and described below.
618
619@deffn {Scheme Procedure} const value
620Return a procedure that accepts any number of arguments and returns
621@var{value}.
622
623@lisp
624(procedure? (const 3)) @result{} #t
625((const 'hello)) @result{} hello
626((const 'hello) 'world) @result{} hello
627@end lisp
628@end deffn
629
630@deffn {Scheme Procedure} negate proc
631Return a procedure with the same arity as @var{proc} that returns the
632@code{not} of @var{proc}'s result.
633
634@lisp
635(procedure? (negate number?)) @result{} #t
636((negate odd?) 2) @result{} #t
637((negate real?) 'dream) @result{} #t
638((negate string-prefix?) "GNU" "GNU Guile")
639 @result{} #f
640(filter (negate number?) '(a 2 "b"))
641 @result{} (a "b")
642@end lisp
643@end deffn
644
df0a1002
BT
645@deffn {Scheme Procedure} compose proc1 proc2 @dots{}
646Compose @var{proc1} with the procedures @var{proc2} @dots{} such that
647the last @var{proc} argument is applied first and @var{proc1} last, and
648return the resulting procedure. The given procedures must have
649compatible arity.
18f06db9
LC
650
651@lisp
652(procedure? (compose 1+ 1-)) @result{} #t
653((compose sqrt 1+ 1+) 2) @result{} 2.0
654((compose 1+ sqrt) 3) @result{} 2.73205080756888
655(eq? (compose 1+) 1+) @result{} #t
656
657((compose zip unzip2) '((1 2) (a b)))
658 @result{} ((1 2) (a b))
659@end lisp
660@end deffn
661
662@deffn {Scheme Procedure} identity x
663Return X.
664@end deffn
665
07d83abe
MV
666@node Procedure Properties
667@subsection Procedure Properties and Meta-information
668
f916cbc4
AW
669In addition to the information that is strictly necessary to run,
670procedures may have other associated information. For example, the
671name of a procedure is information not for the procedure, but about
672the procedure. This meta-information can be accessed via the procedure
673properties interface.
07d83abe 674
f916cbc4
AW
675The first group of procedures in this meta-interface are predicates to
676test whether a Scheme object is a procedure, or a special procedure,
bd5dea48
LC
677respectively. @code{procedure?} is the most general predicates, it
678returns @code{#t} for any kind of procedure.
07d83abe
MV
679
680@rnindex procedure?
681@deffn {Scheme Procedure} procedure? obj
682@deffnx {C Function} scm_procedure_p (obj)
683Return @code{#t} if @var{obj} is a procedure.
684@end deffn
685
07d83abe
MV
686@deffn {Scheme Procedure} thunk? obj
687@deffnx {C Function} scm_thunk_p (obj)
bd5dea48
LC
688Return @code{#t} if @var{obj} is a thunk---a procedure that does
689not accept arguments.
07d83abe
MV
690@end deffn
691
07d83abe 692@cindex procedure properties
f916cbc4
AW
693Procedure properties are general properties associated with
694procedures. These can be the name of a procedure or other relevant
07d83abe
MV
695information, such as debug hints.
696
697@deffn {Scheme Procedure} procedure-name proc
698@deffnx {C Function} scm_procedure_name (proc)
699Return the name of the procedure @var{proc}
700@end deffn
701
702@deffn {Scheme Procedure} procedure-source proc
703@deffnx {C Function} scm_procedure_source (proc)
f916cbc4
AW
704Return the source of the procedure @var{proc}. Returns @code{#f} if
705the source code is not available.
07d83abe
MV
706@end deffn
707
07d83abe
MV
708@deffn {Scheme Procedure} procedure-properties proc
709@deffnx {C Function} scm_procedure_properties (proc)
f916cbc4
AW
710Return the properties associated with @var{proc}, as an association
711list.
07d83abe
MV
712@end deffn
713
f916cbc4
AW
714@deffn {Scheme Procedure} procedure-property proc key
715@deffnx {C Function} scm_procedure_property (proc, key)
716Return the property of @var{proc} with name @var{key}.
07d83abe
MV
717@end deffn
718
719@deffn {Scheme Procedure} set-procedure-properties! proc alist
720@deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
f916cbc4 721Set @var{proc}'s property list to @var{alist}.
07d83abe
MV
722@end deffn
723
f916cbc4
AW
724@deffn {Scheme Procedure} set-procedure-property! proc key value
725@deffnx {C Function} scm_set_procedure_property_x (proc, key, value)
726In @var{proc}'s property list, set the property named @var{key} to
07d83abe
MV
727@var{value}.
728@end deffn
729
730@cindex procedure documentation
731Documentation for a procedure can be accessed with the procedure
732@code{procedure-documentation}.
733
734@deffn {Scheme Procedure} procedure-documentation proc
735@deffnx {C Function} scm_procedure_documentation (proc)
736Return the documentation string associated with @code{proc}. By
737convention, if a procedure contains more than one expression and the
738first expression is a string constant, that string is assumed to contain
739documentation for that procedure.
740@end deffn
741
07d83abe
MV
742
743@node Procedures with Setters
744@subsection Procedures with Setters
745
746@c FIXME::martin: Review me!
747
748@c FIXME::martin: Document `operator struct'.
749
750@cindex procedure with setter
751@cindex setter
752A @dfn{procedure with setter} is a special kind of procedure which
753normally behaves like any accessor procedure, that is a procedure which
754accesses a data structure. The difference is that this kind of
755procedure has a so-called @dfn{setter} attached, which is a procedure
756for storing something into a data structure.
757
758Procedures with setters are treated specially when the procedure appears
759in the special form @code{set!} (REFFIXME). How it works is best shown
760by example.
761
762Suppose we have a procedure called @code{foo-ref}, which accepts two
763arguments, a value of type @code{foo} and an integer. The procedure
764returns the value stored at the given index in the @code{foo} object.
765Let @code{f} be a variable containing such a @code{foo} data
766structure.@footnote{Working definitions would be:
767@lisp
768(define foo-ref vector-ref)
769(define foo-set! vector-set!)
770(define f (make-vector 2 #f))
771@end lisp
772}
773
774@lisp
775(foo-ref f 0) @result{} bar
776(foo-ref f 1) @result{} braz
777@end lisp
778
779Also suppose that a corresponding setter procedure called
780@code{foo-set!} does exist.
781
782@lisp
783(foo-set! f 0 'bla)
784(foo-ref f 0) @result{} bla
785@end lisp
786
787Now we could create a new procedure called @code{foo}, which is a
788procedure with setter, by calling @code{make-procedure-with-setter} with
789the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
790Let us call this new procedure @code{foo}.
791
792@lisp
793(define foo (make-procedure-with-setter foo-ref foo-set!))
794@end lisp
795
796@code{foo} can from now an be used to either read from the data
797structure stored in @code{f}, or to write into the structure.
798
799@lisp
800(set! (foo f 0) 'dum)
801(foo f 0) @result{} dum
802@end lisp
803
804@deffn {Scheme Procedure} make-procedure-with-setter procedure setter
805@deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
806Create a new procedure which behaves like @var{procedure}, but
807with the associated setter @var{setter}.
808@end deffn
809
810@deffn {Scheme Procedure} procedure-with-setter? obj
811@deffnx {C Function} scm_procedure_with_setter_p (obj)
812Return @code{#t} if @var{obj} is a procedure with an
813associated setter procedure.
814@end deffn
815
816@deffn {Scheme Procedure} procedure proc
817@deffnx {C Function} scm_procedure (proc)
3323ec06
NJ
818Return the procedure of @var{proc}, which must be an
819applicable struct.
07d83abe
MV
820@end deffn
821
822@deffn {Scheme Procedure} setter proc
823Return the setter of @var{proc}, which must be either a procedure with
824setter or an operator struct.
825@end deffn
826
165b10dd
AR
827@node Inlinable Procedures
828@subsection Inlinable Procedures
829
43e53d64
LC
830@cindex inlining
831@cindex procedure inlining
165b10dd
AR
832You can define an @dfn{inlinable procedure} by using
833@code{define-inlinable} instead of @code{define}. An inlinable
834procedure behaves the same as a regular procedure, but direct calls will
835result in the procedure body being inlined into the caller.
836
43e53d64
LC
837@cindex partial evaluator
838Bear in mind that starting from version 2.0.3, Guile has a partial
839evaluator that can inline the body of inner procedures when deemed
840appropriate:
841
842@example
843scheme@@(guile-user)> ,optimize (define (foo x)
844 (define (bar) (+ x 3))
845 (* (bar) 2))
846$1 = (define foo
847 (lambda (#@{x 94@}#) (* (+ #@{x 94@}# 3) 2)))
848@end example
849
850@noindent
851The partial evaluator does not inline top-level bindings, though, so
852this is a situation where you may find it interesting to use
853@code{define-inlinable}.
854
165b10dd
AR
855Procedures defined with @code{define-inlinable} are @emph{always}
856inlined, at all direct call sites. This eliminates function call
857overhead at the expense of an increase in code size. Additionally, the
858caller will not transparently use the new definition if the inline
859procedure is redefined. It is not possible to trace an inlined
860procedures or install a breakpoint in it (@pxref{Traps}). For these
861reasons, you should not make a procedure inlinable unless it
862demonstrably improves performance in a crucial way.
863
864In general, only small procedures should be considered for inlining, as
865making large procedures inlinable will probably result in an increase in
866code size. Additionally, the elimination of the call overhead rarely
b3da54d1 867matters for large procedures.
165b10dd 868
df0a1002 869@deffn {Scheme Syntax} define-inlinable (name parameter @dots{}) body1 body2 @dots{}
165b10dd 870Define @var{name} as a procedure with parameters @var{parameter}s and
df0a1002 871bodies @var{body1}, @var{body2}, @enddots{}.
165b10dd 872@end deffn
07d83abe 873
07d83abe
MV
874@c Local Variables:
875@c TeX-master: "guile.texi"
876@c End: