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