Some functions take arguments that only in exceptional cases are different from a default value. Optional arguments makes it possible only to give the extra arguments in the exceptional case.
Two different solutions are presented below.
The most direct us using
opt-lambda. The
opt-lambda form behaves like a normal lambda form, except that a default value can be attached to a parameter by replacing
parameter with
[parameter default-value-expression]. Note that all variables after an optional argument must also have default value expression.
The second solution uses
case-lambda to catch the cases where
the optional arguments are missing. They are then provided in
a recursive call.
The example features the function
count-down. In most cases a count down to 0 is wanted, but the end point can be given.
(define (interval s t)
(if (> s t)
'()
(cons s (interval (+ s 1) t))))
(define count-down
(opt-lambda (n [m 0])
(reverse (interval (+ (- n m) 1) m))))
(count-down 10) (count-down 10 4)
(define count-down
(case-lambda
[(n) (count-down n 0)]
[(n m) (reverse (interval (+ (- n m) 1) m))]))
(count-down 10) (count-down 10 4)
The
case-lambda construct is a primitive in PLT Scheme.
In other Schemes remember to load
SRFI 16 (Syntax for procedures of variable arity. )
The
opt-lambda macro is implemented in terms of
case-lambda.
--
JensAxelSoegaard
--
NoelWelsh
I think it would be best not to require
SRFI-1 to use "iota" in an example. The use looked complicated, and is not standard Scheme, when the intent is to illustrate optional arguments. Below is an R5RS
count-down, but perhaps simpler example like
incremented would be best (if that's not
too simple):
(require (lib "etc.ss"))
(define count-down
(opt-lambda (start (end 0))
(let loop ((i start))
(if (< i end)
'()
(cons i (loop (- i 1)))))))
(require (lib "etc.ss"))
(define incremented
(opt-lambda (number (increment 1))
(+ number increment)))
(incremented 42) (incremented 42 27)
Also we should note that
opt-lambda requires
(lib "etc.ss").
--
NeilVanDyke - 17 May 2004
I renamed
iota to interval and defined without using
SRFI9.
--
JensAxelSoegaard - 21 May 2004
I just did some minor corrections:
- Added ")" at the end of "interval", which was missing.
- Changed the description above "interval", which now uses only s and t parameters to explain the function.
--
RudiBonfiglioli - 01 August 2010