api-procedures.texi 34 KB

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