Warning: This is the manual of the legacy Guile 2.0 series. You may want to read the manual of the current stable series instead.
Next: Keyword Read Syntax, Previous: Why Use Keywords?, Up: Keywords [Contents][Index]
If a procedure wants to support keywords, it should take a rest argument and then use whatever means is convenient to extract keywords and their corresponding arguments from the contents of that rest argument.
The following example illustrates the principle: the code for
make-window
uses a helper procedure called
get-keyword-value
to extract individual keyword arguments from
the rest argument.
(define (get-keyword-value args keyword default) (let ((kv (memq keyword args))) (if (and kv (>= (length kv) 2)) (cadr kv) default))) (define (make-window . args) (let ((depth (get-keyword-value args #:depth screen-depth)) (bg (get-keyword-value args #:bg "white")) (width (get-keyword-value args #:width 800)) (height (get-keyword-value args #:height 100)) …) …))
But you don’t need to write get-keyword-value
. The (ice-9
optargs)
module provides a set of powerful macros that you can use to
implement keyword-supporting procedures like this:
(use-modules (ice-9 optargs)) (define (make-window . args) (let-keywords args #f ((depth screen-depth) (bg "white") (width 800) (height 100)) ...))
Or, even more economically, like this:
(use-modules (ice-9 optargs)) (define* (make-window #:key (depth screen-depth) (bg "white") (width 800) (height 100)) ...)
For further details on let-keywords
, define*
and other
facilities provided by the (ice-9 optargs)
module, see
Optional Arguments.
To handle keyword arguments from procedures implemented in C,
use scm_c_bind_keyword_arguments
(see Keyword Procedures).