gpt4 book ai didi

function - 方案 lambda 函数中的默认参数?

转载 作者:行者123 更新时间:2023-12-02 09:11:42 24 4
gpt4 key购买 nike

我最近开始使用 ChickenScheme,现在我想声明一个带有默认参数(如果未指定)的函数。我在 Racket 网站上找到了这个例子,我知道 Racket 和 ChickenScheme 是不同的,但我认为这些基本的东西是相同的。

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

这是来自 ChickenScheme 解释器的错误:

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)) <--

最佳答案

在普通方案中,您可以使用 dotted tail notation获取附加参数的列表,然后检查此列表以查看是否提供了附加参数:

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

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

 (define greet
(lambda (given #!optional (surname "Smith"))
(string-append "Hello, " given " " surname)))

关于function - 方案 lambda 函数中的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38294805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com