我试图弄清楚如何在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, +]
Run Code Online (Sandbox Code Playgroud)
I've also tried (define (func a [b 0]) (+ a b)) but I get the following error:
Error: execute: unbound symbol: "b" [func]
Run Code Online (Sandbox Code Playgroud)
If it helps I'm using BiwaScheme as used in repl.it
这在 Racket 中效果很好:
(define (func a (b 0)) ; same as [b 0]
(+ a b))
Run Code Online (Sandbox Code Playgroud)
例如:
(func 4)
=> 4
(func 3 2)
=> 5
Run Code Online (Sandbox Code Playgroud)
...但这不是标准语法,它取决于所使用的方案解释器。有处理可变数量参数的语法,它可用于处理具有默认值的可选参数,但它看起来不太漂亮:
(define (func a . b)
(+ a (if (null? b) 0 (car b))))
Run Code Online (Sandbox Code Playgroud)
它是如何工作的?b是一个参数列表。如果为空,则使用零,否则使用第一个元素的值。