I'm trying to figure out how to how to set default or optional parameters in Scheme.
I've tried (define (func a #!optional b) (+ a b))
but I can't find of a way to check if b
is a default parameter, because simply calling (func 1 2)
will give the error:
Error: +: number required, but got #("halt") [func, +]
I've also tried (define (func a [b 0]) (+ a b))
but I get the following error:
Error: execute: unbound symbol: "b" [func]
If it helps I'm using BiwaScheme as used in repl.it
This works fine in Racket:
(define (func a (b 0)) ; same as [b 0]
(+ a b))
For example:
(func 4)
=> 4
(func 3 2)
=> 5
...But it's not standard syntax, it depends on the Scheme interpreter being used. There's syntax for handling a variable number of arguments, it can be used to handle optional arguments with default values, but it won't look as pretty:
(define (func a . b)
(+ a (if (null? b) 0 (car b))))
How does it work? b
is a list of arguments. If it's empty use zero, otherwise use the value of the first element.
Check if your Scheme implementation supports SRFI 89: Optional positional and named parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With