api-procedures.texi 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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,
  4. @c 2011, 2012, 2013, 2024 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 be converted into a list
  58. and 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. @xref{Foreign Functions}, for another interface to call procedures
  107. written in C from Scheme.
  108. @node Compiled Procedures
  109. @subsection Compiled Procedures
  110. The evaluation strategy given in @ref{Lambda} describes how procedures
  111. are @dfn{interpreted}. Interpretation operates directly on expanded
  112. Scheme source code, recursively calling the evaluator to obtain the
  113. value of nested expressions.
  114. Most procedures are compiled, however. This means that Guile has done
  115. some pre-computation on the procedure, to determine what it will need to
  116. do each time the procedure runs. Compiled procedures run faster than
  117. interpreted procedures.
  118. Loading files is the normal way that compiled procedures come to
  119. being. If Guile sees that a file is uncompiled, or that its compiled
  120. file is out of date, it will attempt to compile the file when it is
  121. loaded, and save the result to disk. Procedures can be compiled at
  122. runtime as well. @xref{Read/Load/Eval/Compile}, for more information
  123. on runtime compilation.
  124. Compiled procedures, also known as @dfn{programs}, respond to all
  125. procedures that operate on procedures: you can pass a program to
  126. @code{procedure?}, @code{procedure-name}, and so on (@pxref{Procedure
  127. Properties}). In addition, there are a few more accessors for low-level
  128. details on programs.
  129. Most people won't need to use the routines described in this section,
  130. but it's good to have them documented. You'll have to include the
  131. appropriate module first, though:
  132. @example
  133. (use-modules (system vm program))
  134. @end example
  135. @deffn {Scheme Procedure} program? obj
  136. @deffnx {C Function} scm_program_p (obj)
  137. Returns @code{#t} if @var{obj} is a compiled procedure, or @code{#f}
  138. otherwise.
  139. @end deffn
  140. @deffn {Scheme Procedure} program-code program
  141. @deffnx {C Function} scm_program_code (program)
  142. Returns the address of the program's entry, as an integer. This address
  143. is mostly useful to procedures in @code{(system vm debug)}.
  144. @end deffn
  145. @deffn {Scheme Procedure} program-num-free-variable program
  146. @deffnx {C Function} scm_program_num_free_variables (program)
  147. Return the number of free variables captured by this program.
  148. @end deffn
  149. @deffn {Scheme Procedure} program-free-variable-ref program n
  150. @deffnx {C Function} scm_program_free_variable-ref (program, n)
  151. @deffnx {Scheme Procedure} program-free-variable-set! program n val
  152. @deffnx {C Function} scm_program_free_variable_set_x (program, n, val)
  153. Accessors for a program's free variables. Some of the values captured
  154. are actually in variable ``boxes''. @xref{Variables and the VM}, for
  155. more information.
  156. Users must not modify the returned value unless they think they're
  157. really clever.
  158. @end deffn
  159. @deffn {Scheme Procedure} program-sources program
  160. @deffnx {Scheme Procedure} source:addr source
  161. @deffnx {Scheme Procedure} source:line source
  162. @deffnx {Scheme Procedure} source:column source
  163. @deffnx {Scheme Procedure} source:file source
  164. Source location annotations for programs, along with their accessors.
  165. Source location information propagates through the compiler and ends
  166. up being serialized to the program's metadata. This information is
  167. keyed by the offset of the instruction pointer within the object code
  168. of the program. Specifically, it is keyed on the @code{ip} @emph{just
  169. following} an instruction, so that backtraces can find the source
  170. location of a call that is in progress.
  171. @end deffn
  172. @deffn {Scheme Procedure} program-arities program
  173. @deffnx {C Function} scm_program_arities (program)
  174. @deffnx {Scheme Procedure} program-arity program ip
  175. @deffnx {Scheme Procedure} arity:start arity
  176. @deffnx {Scheme Procedure} arity:end arity
  177. @deffnx {Scheme Procedure} arity:nreq arity
  178. @deffnx {Scheme Procedure} arity:nopt arity
  179. @deffnx {Scheme Procedure} arity:rest? arity
  180. @deffnx {Scheme Procedure} arity:kw arity
  181. @deffnx {Scheme Procedure} arity:allow-other-keys? arity
  182. Accessors for a representation of the ``arity'' of a program.
  183. The normal case is that a procedure has one arity. For example,
  184. @code{(lambda (x) x)}, takes one required argument, and that's it. One
  185. could access that number of required arguments via @code{(arity:nreq
  186. (program-arities (lambda (x) x)))}. Similarly, @code{arity:nopt} gets
  187. the number of optional arguments, and @code{arity:rest?} returns a true
  188. value if the procedure has a rest arg.
  189. @code{arity:kw} returns a list of @code{(@var{kw} . @var{idx})} pairs,
  190. if the procedure has keyword arguments. The @var{idx} refers to the
  191. @var{idx}th local variable; @xref{Variables and the VM}, for more
  192. information. Finally @code{arity:allow-other-keys?} returns a true
  193. value if other keys are allowed. @xref{Optional Arguments}, for more
  194. information.
  195. So what about @code{arity:start} and @code{arity:end}, then? They
  196. return the range of bytes in the program's bytecode for which a given
  197. arity is valid. You see, a procedure can actually have more than one
  198. arity. The question, ``what is a procedure's arity'' only really makes
  199. sense at certain points in the program, delimited by these
  200. @code{arity:start} and @code{arity:end} values.
  201. @end deffn
  202. @deffn {Scheme Procedure} program-arguments-alist program [ip]
  203. Return an association list describing the arguments that @var{program} accepts, or
  204. @code{#f} if the information cannot be obtained.
  205. The alist keys that are currently defined are `required', `optional',
  206. `keyword', `allow-other-keys?', and `rest'. For example:
  207. @example
  208. (program-arguments-alist
  209. (lambda* (a b #:optional c #:key (d 1) #:rest e)
  210. #t)) @result{}
  211. ((required . (a b))
  212. (optional . (c))
  213. (keyword . ((#:d . 4)))
  214. (allow-other-keys? . #f)
  215. (rest . d))
  216. @end example
  217. @end deffn
  218. @deffn {Scheme Procedure} program-lambda-list program [ip]
  219. Return a representation of the arguments of @var{program} as a lambda
  220. list, or @code{#f} if this information is not available.
  221. For example:
  222. @example
  223. (program-lambda-list
  224. (lambda* (a b #:optional c #:key (d 1) #:rest e)
  225. #t)) @result{}
  226. @end example
  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{}] @* @
  253. [#:optional vardef@dots{}] @* @
  254. [#:key vardef@dots{} [#:allow-other-keys]] @* @
  255. [#:rest var | . var]) @* @
  256. body1 body2 @dots{}
  257. @sp 1
  258. Create a procedure which takes optional and/or keyword arguments
  259. specified with @code{#:optional} and @code{#:key}. For example,
  260. @lisp
  261. (lambda* (a b #:optional c d . e) '())
  262. @end lisp
  263. is a procedure with fixed arguments @var{a} and @var{b}, optional
  264. arguments @var{c} and @var{d}, and rest argument @var{e}. If the
  265. optional arguments are omitted in a call, the variables for them are
  266. bound to @code{#f}.
  267. @fnindex define*
  268. Likewise, @code{define*} is syntactic sugar for defining procedures
  269. using @code{lambda*}.
  270. @code{lambda*} can also make procedures with keyword arguments. For
  271. example, a procedure defined like this:
  272. @lisp
  273. (define* (sir-yes-sir #:key action how-high)
  274. (list action how-high))
  275. @end lisp
  276. can be called as @code{(sir-yes-sir #:action 'jump)},
  277. @code{(sir-yes-sir #:how-high 13)}, @code{(sir-yes-sir #:action
  278. 'lay-down #:how-high 0)}, or just @code{(sir-yes-sir)}. Whichever
  279. arguments are given as keywords are bound to values (and those not
  280. given are @code{#f}).
  281. Optional and keyword arguments can also have default values to take
  282. when not present in a call, by giving a two-element list of variable
  283. name and expression. For example in
  284. @lisp
  285. (define* (frob foo #:optional (bar 42) #:key (baz 73))
  286. (list foo bar baz))
  287. @end lisp
  288. @var{foo} is a fixed argument, @var{bar} is an optional argument with
  289. default value 42, and baz is a keyword argument with default value 73.
  290. Default value expressions are not evaluated unless they are needed,
  291. and until the procedure is called.
  292. Normally it's an error if a call has keywords other than those
  293. specified by @code{#:key}, but adding @code{#:allow-other-keys} to the
  294. definition (after the keyword argument declarations) will ignore
  295. unknown keywords.
  296. If a call has a keyword given twice, the last value is used. For
  297. example,
  298. @lisp
  299. (define* (flips #:key (heads 0) (tails 0))
  300. (display (list heads tails)))
  301. (flips #:heads 37 #:tails 42 #:heads 99)
  302. @print{} (99 42)
  303. @end lisp
  304. @code{#:rest} is a synonym for the dotted syntax rest argument. The
  305. argument lists @code{(a . b)} and @code{(a #:rest b)} are equivalent
  306. in all respects. This is provided for more similarity to DSSSL,
  307. MIT-Scheme and Kawa among others, as well as for refugees from other
  308. Lisp dialects.
  309. When @code{#:key} is used together with a rest argument, the keyword
  310. parameters in a call all remain in the rest list. This is the same as
  311. Common Lisp. For example,
  312. @lisp
  313. ((lambda* (#:key (x 0) #:allow-other-keys #:rest r)
  314. (display r))
  315. #:x 123 #:y 456)
  316. @print{} (#:x 123 #:y 456)
  317. @end lisp
  318. @code{#:optional} and @code{#:key} establish their bindings
  319. successively, from left to right. This means default expressions can
  320. refer back to prior parameters, for example
  321. @lisp
  322. (lambda* (start #:optional (end (+ 10 start)))
  323. (do ((i start (1+ i)))
  324. ((> i end))
  325. (display i)))
  326. @end lisp
  327. The exception to this left-to-right scoping rule is the rest argument.
  328. If there is a rest argument, it is bound after the optional arguments,
  329. but before the keyword arguments.
  330. @end deffn
  331. @node ice-9 optargs
  332. @subsubsection (ice-9 optargs)
  333. Before Guile 2.0, @code{lambda*} and @code{define*} were implemented
  334. using macros that processed rest list arguments. This was not optimal,
  335. as calling procedures with optional arguments had to allocate rest
  336. lists at every procedure invocation. Guile 2.0 improved this
  337. situation by bringing optional and keyword arguments into Guile's
  338. core.
  339. However there are occasions in which you have a list and want to parse
  340. it for optional or keyword arguments. Guile's @code{(ice-9 optargs)}
  341. provides some macros to help with that task.
  342. The syntax @code{let-optional} and @code{let-optional*} are for
  343. destructuring rest argument lists and giving names to the various list
  344. elements. @code{let-optional} binds all variables simultaneously, while
  345. @code{let-optional*} binds them sequentially, consistent with @code{let}
  346. and @code{let*} (@pxref{Local Bindings}).
  347. @deffn {library syntax} let-optional rest-arg (binding @dots{}) body1 body2 @dots{}
  348. @deffnx {library syntax} let-optional* rest-arg (binding @dots{}) body1 body2 @dots{}
  349. These two macros give you an optional argument interface that is very
  350. @dfn{Schemey} and introduces no fancy syntax. They are compatible with
  351. the scsh macros of the same name, but are slightly extended. Each of
  352. @var{binding} may be of one of the forms @var{var} or @code{(@var{var}
  353. @var{default-value})}. @var{rest-arg} should be the rest-argument of the
  354. procedures these are used from. The items in @var{rest-arg} are
  355. sequentially bound to the variable names are given. When @var{rest-arg}
  356. runs out, the remaining vars are bound either to the default values or
  357. @code{#f} if no default value was specified. @var{rest-arg} remains
  358. bound to whatever may have been left of @var{rest-arg}.
  359. After binding the variables, the expressions @var{body1} @var{body2} @dots{}
  360. are evaluated in order.
  361. @end deffn
  362. Similarly, @code{let-keywords} and @code{let-keywords*} extract values
  363. from keyword style argument lists, binding local variables to those
  364. values or to defaults.
  365. @deffn {library syntax} let-keywords args allow-other-keys? (binding @dots{}) body1 body2 @dots{}
  366. @deffnx {library syntax} let-keywords* args allow-other-keys? (binding @dots{}) body1 body2 @dots{}
  367. @var{args} is evaluated and should give a list of the form
  368. @code{(#:keyword1 value1 #:keyword2 value2 @dots{})}. The
  369. @var{binding}s are variables and default expressions, with the variables
  370. to be set (by name) from the keyword values. The @var{body1}
  371. @var{body2} @dots{} forms are then evaluated and the last is the
  372. result. An example will make the syntax clearest,
  373. @example
  374. (define args '(#:xyzzy "hello" #:foo "world"))
  375. (let-keywords args #t
  376. ((foo "default for foo")
  377. (bar (string-append "default" "for" "bar")))
  378. (display foo)
  379. (display ", ")
  380. (display bar))
  381. @print{} world, defaultforbar
  382. @end example
  383. The binding for @code{foo} comes from the @code{#:foo} keyword in
  384. @code{args}. But the binding for @code{bar} is the default in the
  385. @code{let-keywords}, since there's no @code{#:bar} in the args.
  386. @var{allow-other-keys?} is evaluated and controls whether unknown
  387. keywords are allowed in the @var{args} list. When true other keys are
  388. ignored (such as @code{#:xyzzy} in the example), when @code{#f} an
  389. error is thrown for anything unknown.
  390. @end deffn
  391. @code{(ice-9 optargs)} also provides some more @code{define*} sugar,
  392. which is not so useful with modern Guile coding, but still supported:
  393. @code{define*-public} is the @code{lambda*} version of
  394. @code{define-public}; @code{defmacro*} and @code{defmacro*-public}
  395. exist for defining macros with the improved argument list handling
  396. possibilities. The @code{-public} versions not only define the
  397. procedures/macros, but also export them from the current module.
  398. @deffn {library syntax} define*-public formals body1 body2 @dots{}
  399. Like a mix of @code{define*} and @code{define-public}.
  400. @end deffn
  401. @deffn {library syntax} defmacro* name formals body1 body2 @dots{}
  402. @deffnx {library syntax} defmacro*-public name formals body1 body2 @dots{}
  403. These are just like @code{defmacro} and @code{defmacro-public} except that they
  404. take @code{lambda*}-style extended parameter lists, where @code{#:optional},
  405. @code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
  406. semantics. Here is an example of a macro with an optional argument:
  407. @lisp
  408. (defmacro* transmogrify (a #:optional b)
  409. (a 1))
  410. @end lisp
  411. @end deffn
  412. @node Case-lambda
  413. @subsection Case-lambda
  414. @cindex SRFI-16
  415. @cindex variable arity
  416. @cindex arity, variable
  417. R5RS's rest arguments are indeed useful and very general, but they
  418. often aren't the most appropriate or efficient means to get the job
  419. done. For example, @code{lambda*} is a much better solution to the
  420. optional argument problem than @code{lambda} with rest arguments.
  421. @fnindex case-lambda
  422. Likewise, @code{case-lambda} works well for when you want one
  423. procedure to do double duty (or triple, or ...), without the penalty
  424. of consing a rest list.
  425. For example:
  426. @lisp
  427. (define (make-accum n)
  428. (case-lambda
  429. (() n)
  430. ((m) (set! n (+ n m)) n)))
  431. (define a (make-accum 20))
  432. (a) @result{} 20
  433. (a 10) @result{} 30
  434. (a) @result{} 30
  435. @end lisp
  436. The value returned by a @code{case-lambda} form is a procedure which
  437. matches the number of actual arguments against the formals in the
  438. various clauses, in order. The first matching clause is selected, the
  439. corresponding values from the actual parameter list are bound to the
  440. variable names in the clauses and the body of the clause is evaluated.
  441. If no clause matches, an error is signaled.
  442. The syntax of the @code{case-lambda} form is defined in the following
  443. EBNF grammar. @dfn{Formals} means a formal argument list just like
  444. with @code{lambda} (@pxref{Lambda}).
  445. @example
  446. @group
  447. <case-lambda>
  448. --> (case-lambda <case-lambda-clause>*)
  449. --> (case-lambda <docstring> <case-lambda-clause>*)
  450. <case-lambda-clause>
  451. --> (<formals> <definition-or-command>*)
  452. <formals>
  453. --> (<identifier>*)
  454. | (<identifier>* . <identifier>)
  455. | <identifier>
  456. @end group
  457. @end example
  458. Rest lists can be useful with @code{case-lambda}:
  459. @lisp
  460. (define plus
  461. (case-lambda
  462. "Return the sum of all arguments."
  463. (() 0)
  464. ((a) a)
  465. ((a b) (+ a b))
  466. ((a b . rest) (apply plus (+ a b) rest))))
  467. (plus 1 2 3) @result{} 6
  468. @end lisp
  469. @fnindex case-lambda*
  470. Also, for completeness. Guile defines @code{case-lambda*} as well,
  471. which is like @code{case-lambda}, except with @code{lambda*} clauses.
  472. A @code{case-lambda*} clause matches if the arguments fill the
  473. required arguments, but are not too many for the optional and/or rest
  474. arguments.
  475. Keyword arguments are possible with @code{case-lambda*} as well, but
  476. they do not contribute to the ``matching'' behavior, and their
  477. interactions with required, optional, and rest arguments can be
  478. surprising.
  479. For the purposes of @code{case-lambda*} (and of @code{case-lambda}, as a
  480. special case), a clause @dfn{matches} if it has enough required
  481. arguments, and not too many positional arguments. The required
  482. arguments are any arguments before the @code{#:optional}, @code{#:key},
  483. and @code{#:rest} arguments. @dfn{Positional} arguments are the
  484. required arguments, together with the optional arguments.
  485. In the absence of @code{#:key} or @code{#:rest} arguments, it's easy to
  486. see how there could be too many positional arguments: you pass 5
  487. arguments to a function that only takes 4 arguments, including optional
  488. arguments. If there is a @code{#:rest} argument, there can never be too
  489. many positional arguments: any application with enough required
  490. arguments for a clause will match that clause, even if there are also
  491. @code{#:key} arguments.
  492. Otherwise, for applications to a clause with @code{#:key} arguments (and
  493. without a @code{#:rest} argument), a clause will match there only if
  494. there are enough required arguments and if the next argument after
  495. binding required and optional arguments, if any, is a keyword. For
  496. efficiency reasons, Guile is currently unable to include keyword
  497. arguments in the matching algorithm. Clauses match on positional
  498. arguments only, not by comparing a given keyword to the available set of
  499. keyword arguments that a function has.
  500. Some examples follow.
  501. @example
  502. (define f
  503. (case-lambda*
  504. ((a #:optional b) 'clause-1)
  505. ((a #:optional b #:key c) 'clause-2)
  506. ((a #:key d) 'clause-3)
  507. ((#:key e #:rest f) 'clause-4)))
  508. (f) @result{} clause-4
  509. (f 1) @result{} clause-1
  510. (f) @result{} clause-4
  511. (f #:e 10) clause-1
  512. (f 1 #:foo) clause-1
  513. (f 1 #:c 2) clause-2
  514. (f #:a #:b #:c #:d #:e) clause-4
  515. ;; clause-2 will match anything that clause-3 would match.
  516. (f 1 #:d 2) @result{} error: bad keyword args in clause 2
  517. @end example
  518. Don't forget that the clauses are matched in order, and the first
  519. matching clause will be taken. This can result in a keyword being bound
  520. to a required argument, as in the case of @code{f #:e 10}.
  521. @node Higher-Order Functions
  522. @subsection Higher-Order Functions
  523. @cindex higher-order functions
  524. As a functional programming language, Scheme allows the definition of
  525. @dfn{higher-order functions}, i.e., functions that take functions as
  526. arguments and/or return functions. Utilities to derive procedures from
  527. other procedures are provided and described below.
  528. @deffn {Scheme Procedure} const value
  529. Return a procedure that accepts any number of arguments and returns
  530. @var{value}.
  531. @lisp
  532. (procedure? (const 3)) @result{} #t
  533. ((const 'hello)) @result{} hello
  534. ((const 'hello) 'world) @result{} hello
  535. @end lisp
  536. @end deffn
  537. @deffn {Scheme Procedure} negate proc
  538. Return a procedure with the same arity as @var{proc} that returns the
  539. @code{not} of @var{proc}'s result.
  540. @lisp
  541. (procedure? (negate number?)) @result{} #t
  542. ((negate odd?) 2) @result{} #t
  543. ((negate real?) 'dream) @result{} #t
  544. ((negate string-prefix?) "GNU" "GNU Guile")
  545. @result{} #f
  546. (filter (negate number?) '(a 2 "b"))
  547. @result{} (a "b")
  548. @end lisp
  549. @end deffn
  550. @deffn {Scheme Procedure} compose proc1 proc2 @dots{}
  551. Compose @var{proc1} with the procedures @var{proc2} @dots{} such that
  552. the last @var{proc} argument is applied first and @var{proc1} last, and
  553. return the resulting procedure. The given procedures must have
  554. compatible arity.
  555. @lisp
  556. (procedure? (compose 1+ 1-)) @result{} #t
  557. ((compose sqrt 1+ 1+) 2) @result{} 2.0
  558. ((compose 1+ sqrt) 3) @result{} 2.73205080756888
  559. (eq? (compose 1+) 1+) @result{} #t
  560. ((compose zip unzip2) '((1 2) (a b)))
  561. @result{} ((1 2) (a b))
  562. @end lisp
  563. @end deffn
  564. @deffn {Scheme Procedure} identity x
  565. Return X.
  566. @end deffn
  567. @deffn {Scheme Procedure} and=> value proc
  568. When @var{value} is @code{#f}, return @code{#f}. Otherwise, return
  569. @code{(@var{proc} @var{value})}.
  570. @end deffn
  571. @node Procedure Properties
  572. @subsection Procedure Properties and Meta-information
  573. In addition to the information that is strictly necessary to run,
  574. procedures may have other associated information. For example, the
  575. name of a procedure is information not for the procedure, but about
  576. the procedure. This meta-information can be accessed via the procedure
  577. properties interface.
  578. @rnindex procedure?
  579. @deffn {Scheme Procedure} procedure? obj
  580. @deffnx {C Function} scm_procedure_p (obj)
  581. Return @code{#t} if @var{obj} is a procedure.
  582. @end deffn
  583. @deffn {Scheme Procedure} thunk? obj
  584. @deffnx {C Function} scm_thunk_p (obj)
  585. Return @code{#t} if @var{obj} is a procedure that can be called with
  586. zero arguments. @xref{Compiled Procedures}, to get more information
  587. on what arguments a procedure will accept.
  588. @end deffn
  589. @cindex procedure properties
  590. Procedure properties are general properties associated with
  591. procedures. These can be the name of a procedure or other relevant
  592. information, such as debug hints.
  593. The most general way to associate a property of a procedure is
  594. programmatically:
  595. @deffn {Scheme Procedure} procedure-property proc key
  596. @deffnx {C Function} scm_procedure_property (proc, key)
  597. Return the property of @var{proc} with name @var{key}, or @code{#f} if
  598. not found.
  599. @end deffn
  600. @deffn {Scheme Procedure} set-procedure-property! proc key value
  601. @deffnx {C Function} scm_set_procedure_property_x (proc, key, value)
  602. Set @var{proc}'s property named @var{key} to @var{value}.
  603. @end deffn
  604. However, there is a more efficient interface that allows constant
  605. properties to be embedded into compiled binaries in a way that does
  606. not incur any overhead until someone asks for the property: initial
  607. non-tail elements of the body of a lambda expression that are literal
  608. vectors of pairs are interpreted as declaring procedure properties.
  609. This is easiest to see with an example:
  610. @example
  611. (define proc
  612. (lambda args
  613. #((a . "hey") (b . "ho")) ;; procedure properties!
  614. 42))
  615. (procedure-property proc 'a) ; @result{} "hey"
  616. (procedure-property proc 'b) ; @result{} "ho"
  617. @end example
  618. There is a shorthand for declaring the @code{documentation} property,
  619. which is a literal string instead of a literal vector:
  620. @example
  621. (define proc
  622. (lambda args
  623. "This is a docstring."
  624. 42))
  625. (procedure-property proc 'documentation)
  626. ;; @result{} "This is a docstring."
  627. @end example
  628. Calling @code{procedure-property} with a key of @code{documentation}
  629. is exactly the same as calling @code{procedure-documentation}.
  630. Similarly, @code{procedure-name} is the same as the @code{name}
  631. procedure property, and @code{procedure-source} is for the
  632. @code{source} property.
  633. @deffn {Scheme Procedure} procedure-name proc
  634. @deffnx {C Function} scm_procedure_name (proc)
  635. @deffnx {Scheme Procedure} procedure-source proc
  636. @deffnx {C Function} scm_procedure_source (proc)
  637. @deffnx {Scheme Procedure} procedure-documentation proc
  638. @deffnx {C Function} scm_procedure_documentation (proc)
  639. Return the value of the @code{name}, @code{source}, or
  640. @code{documentation} property for @var{proc}, or @code{#f} if no
  641. property is set.
  642. @end deffn
  643. One can also work on the entire set of procedure properties.
  644. @deffn {Scheme Procedure} procedure-properties proc
  645. @deffnx {C Function} scm_procedure_properties (proc)
  646. Return the properties associated with @var{proc}, as an association
  647. list.
  648. @end deffn
  649. @deffn {Scheme Procedure} set-procedure-properties! proc alist
  650. @deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
  651. Set @var{proc}'s property list to @var{alist}.
  652. @end deffn
  653. @node Procedures with Setters
  654. @subsection Procedures with Setters
  655. @c FIXME::martin: Review me!
  656. @c FIXME::martin: Document `operator struct'.
  657. @cindex procedure with setter
  658. @cindex setter
  659. A @dfn{procedure with setter} is a special kind of procedure which
  660. normally behaves like any accessor procedure, that is a procedure which
  661. accesses a data structure. The difference is that this kind of
  662. procedure has a so-called @dfn{setter} attached, which is a procedure
  663. for storing something into a data structure.
  664. Procedures with setters are treated specially when the procedure appears
  665. in the special form @code{set!}. @c (REFFIXME)
  666. How it works is best shown by example.
  667. Suppose we have a procedure called @code{foo-ref}, which accepts two
  668. arguments, a value of type @code{foo} and an integer. The procedure
  669. returns the value stored at the given index in the @code{foo} object.
  670. Let @code{f} be a variable containing such a @code{foo} data
  671. structure.@footnote{Working definitions would be:
  672. @lisp
  673. (define foo-ref vector-ref)
  674. (define foo-set! vector-set!)
  675. (define f (make-vector 2 #f))
  676. @end lisp
  677. }
  678. @lisp
  679. (foo-ref f 0) @result{} bar
  680. (foo-ref f 1) @result{} braz
  681. @end lisp
  682. Also suppose that a corresponding setter procedure called
  683. @code{foo-set!} does exist.
  684. @lisp
  685. (foo-set! f 0 'bla)
  686. (foo-ref f 0) @result{} bla
  687. @end lisp
  688. Now we could create a new procedure called @code{foo}, which is a
  689. procedure with setter, by calling @code{make-procedure-with-setter} with
  690. the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
  691. Let us call this new procedure @code{foo}.
  692. @lisp
  693. (define foo (make-procedure-with-setter foo-ref foo-set!))
  694. @end lisp
  695. @code{foo} can from now on be used to either read from the data
  696. structure stored in @code{f}, or to write into the structure.
  697. @lisp
  698. (set! (foo f 0) 'dum)
  699. (foo f 0) @result{} dum
  700. @end lisp
  701. @deffn {Scheme Procedure} make-procedure-with-setter procedure setter
  702. @deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
  703. Create a new procedure which behaves like @var{procedure}, but
  704. with the associated setter @var{setter}.
  705. @end deffn
  706. @deffn {Scheme Procedure} procedure-with-setter? obj
  707. @deffnx {C Function} scm_procedure_with_setter_p (obj)
  708. Return @code{#t} if @var{obj} is a procedure with an
  709. associated setter procedure.
  710. @end deffn
  711. @deffn {Scheme Procedure} procedure proc
  712. @deffnx {C Function} scm_procedure (proc)
  713. Return the procedure of @var{proc}, which must be an
  714. applicable struct.
  715. @end deffn
  716. @deffn {Scheme Procedure} setter proc
  717. Return the setter of @var{proc}, which must be either a procedure with
  718. setter or an operator struct.
  719. @end deffn
  720. @node Inlinable Procedures
  721. @subsection Inlinable Procedures
  722. @cindex inlining
  723. @cindex procedure inlining
  724. You can define an @dfn{inlinable procedure} by using
  725. @code{define-inlinable} instead of @code{define}. An inlinable
  726. procedure behaves the same as a regular procedure, but direct calls will
  727. result in the procedure body being inlined into the caller.
  728. @cindex partial evaluator
  729. Bear in mind that starting from version 2.0.3, Guile has a partial
  730. evaluator that can inline the body of inner procedures when deemed
  731. appropriate:
  732. @example
  733. scheme@@(guile-user)> ,optimize (define (foo x)
  734. (define (bar) (+ x 3))
  735. (* (bar) 2))
  736. $1 = (define foo
  737. (lambda (#@{x 94@}#) (* (+ #@{x 94@}# 3) 2)))
  738. @end example
  739. @noindent
  740. The partial evaluator does not inline top-level bindings, though, so
  741. this is a situation where you may find it interesting to use
  742. @code{define-inlinable}.
  743. Procedures defined with @code{define-inlinable} are @emph{always}
  744. inlined, at all direct call sites. This eliminates function call
  745. overhead at the expense of an increase in code size. Additionally, the
  746. caller will not transparently use the new definition if the inline
  747. procedure is redefined. It is not possible to trace an inlined
  748. procedures or install a breakpoint in it (@pxref{Traps}). For these
  749. reasons, you should not make a procedure inlinable unless it
  750. demonstrably improves performance in a crucial way.
  751. In general, only small procedures should be considered for inlining, as
  752. making large procedures inlinable will probably result in an increase in
  753. code size. Additionally, the elimination of the call overhead rarely
  754. matters for large procedures.
  755. @deffn {Scheme Syntax} define-inlinable (name parameter @dots{}) body1 body2 @dots{}
  756. Define @var{name} as a procedure with parameters @var{parameter}s and
  757. bodies @var{body1}, @var{body2}, @enddots{}.
  758. @end deffn
  759. @c Local Variables:
  760. @c TeX-master: "guile.texi"
  761. @c End: