How to set default or optional parameters in schem

2019-05-09 08:35发布

问题:

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

回答1:

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.



回答2:

Check if your Scheme implementation supports SRFI 89: Optional positional and named parameters.



标签: scheme lisp