api-procedures.texi 34 KB

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