api-procedures.texi 32 KB

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