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