2

I recently started using ChickenScheme and now I want to declare a function with default argument (if not specified). I found this example on the Racket site, I know Racket and ChickenScheme are different but I thought that these basic things were the same.

(define greet
  (lambda (given [surname "Smith"])
    (string-append "Hello, " given " " surname)))

This is the error from the ChickenScheme interpreter:

Error: during expansion of (lambda ...) - in `lambda' - lambda-list expected: (lambda (given (surname "Smith")) (string-append "Hello, " given " " surname))

Call history:

<syntax>      (define greet (lambda (given (surname "Smith")) (string-append "Hello, " given " " surname)))
<syntax>      (##core#set! greet (lambda (given (surname "Smith")) (string-append "Hello, " given " " surname)))
<syntax>      (lambda (given (surname "Smith")) (string-append "Hello, " given " " surname))    <--
4

2 回答 2

5

在普通的 Scheme 中,您可以使用点尾表示法来获取附加参数的列表,然后检查此列表以查看是否提供了额外的参数:

(define greet
   (lambda (given . rest)
     (let ((surname (if (pair? rest) (car rest) "Smith")))
       (string-append "Hello, " given " " surname))))

因为这不是很方便,所以不同的 Scheme 系统为此提供了不同的替代方案。在 CHICKEN 中,我们支持DSSSL 注释,因此您可以这样做:

 (define greet
   (lambda (given #!optional (surname "Smith"))
     (string-append "Hello, " given " " surname)))
于 2016-07-10T19:36:07.683 回答
3

Racket 中可选参数的语法实际上是非标准的,所以不要指望其他解释器来实现它。在 Scheme 中,标准功能是在 RxRS Scheme 报告中定义的,其中R7RS是最新的。但不要害怕 - 在鸡计划中,您可以使用optional

[syntax] (optional ARGS DEFAULT)

将此形式用于采用单个可选参数的过程。如果 ARGS 是空列表 DEFAULT 被评估并返回,否则列表的第一个元素 ARGS。如果 ARGS 包含多个值,则为错误。

像这样使用它:

(define (greet given . surname)
  (string-append "Hello, " given " " (optional surname "Smith")))
于 2016-07-10T19:33:49.063 回答