Scheme - 可选参数和默认值
我目前正在研究Scheme,以及我了解它的方式,过程可以采用任意数量的参数。Scheme - 可选参数和默认值
我一直在尝试玩这个,但我正在努力去理解这个概念。
例如,假设我想根据用户提供的信息编写欢迎消息。
如果用户提供了一个名字和姓氏,节目喊写:
Welcome, <FIRST> <LAST>!
;; <FIRST> = "Julius", <LAST>= "Caesar"
Welcome, Julius Caesar!
否则,程序应该是指一个默认值,指定为:
Welcome, Anonymous Person!
我有以下大纲为我的代码,但如何确定这一点挣扎。
(define (welcome . args)
(let (('first <user_first>/"Anonymous")
('last <user_last>/"Person"))
(display (string-append "Welcome, " first " " last "!"))))
用法示例:
(welcome) ;;no arguments
--> Welcome, Anonymous Person!
(welcome 'first "John") ;;one argument
--> Welcome, John Person!
(welcome 'first "John" 'last "Doe") ;;two arguments
--> Welcome, John Doe!
任何帮助,不胜感激!
在Racket中,他们的方式是使用keyword arguments。您可以定义关键字参数我的写作#:keyword argument-id
声明参数时的功能:
(define (welcome #:first first-name #:last last-name)
(display (string-append "Welcome, " first-name " " last-name "!")))
,你可以这样调用:
> (welcome #:first "John" #:last "Doe")
Welcome, John Doe!
但是,你想要的是让他们可选的。为此,您可以在参数声明中编写#:keyword [argument-id default-value]
。
(define (welcome #:first [first-name "Anonymous"] #:last [last-name "Person"])
(display (string-append "Welcome, " first-name " " last-name "!")))
因此,如果在某个函数调用中不使用该关键字,则会填充默认值。
> (welcome)
Welcome, Anonymous Person!
> (welcome #:first "John")
Welcome, John Person!
> (welcome #:first "John" #:last "Doe")
Welcome, John Doe!
> (welcome #:last "Doe" #:first "John")
Welcome, John Doe!
@Alex Knauth的回答非常好。这是我不知道的。
下面是一个选择,但它不是很灵活
(define (welcome (first "Anonymous") (last "Person"))
(displayln (string-append "Welcome, " first " " last "!")))
这工作得很好地与您的基本要求
> (welcome)
Welcome, Anonymous Person!
> (welcome "John")
Welcome, John Person!
> (welcome "John" "Doe")
Welcome, John Doe!
然而,亚历克斯的解决方案有两个明显的优势。
- 的参数可以以任何顺序
- 姓氏叫,而不名字
你的答案可以通过定义'(定义欢迎 (拉姆达ARGS (字符串追加改善 “欢迎” (或(assq-REF ARGS“第一) “匿名”) “” (或( assq-ref args'last)“Person”))))'然后调用'(welcome)(first。“John”)'(last。“Doe”))'。 –
您应该提交此问题作为问题的另一个答案。这是一个很好的选择,但是如果我想将关键的参数关联起来,我可能会使用Alex的解决方案。感谢分享^ _ ^ – naomik
这可以指定不带参数的任意数量。 – Zelphir
我不打算让它取任意数量的参数;如果你需要的话,你可以编写'(define(welcome#:first first-name#:last last-name。rest-args)...)' –