2016-04-28 72 views
2

我目前正在研究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! 

任何幫助,不勝感激!

回答

1

在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! 
+0

這可以指定不帶參數的任意數量。 – Zelphir

+1

我不打算讓它取任意數量的參數;如果你需要的話,你可以編寫'(define(welcome#:first first-name#:last last-name。rest-args)...)' –

0

@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! 

然而,亞歷克斯的解決方案有兩個明顯的優勢。

  1. 的參數可以以任何順序
  2. 姓氏叫,而不名字
+1

你的答案可以通過定義'(定義歡迎 (拉姆達ARGS (字符串追加改善 「歡迎」 (或(assq-REF ARGS「第一) 「匿名」) 「」 (或( assq-ref args'last)「Person」))))'然後調用'(welcome)(first。「John」)'(last。「Doe」))'。 –

+1

您應該提交此問題作爲問題的另一個答案。這是一個很好的選擇,但是如果我想將關鍵的參數關聯起來,我可能會使用Alex的解決方案。感謝分享^ _ ^ – naomik