Lisp - 可選引數



你可以使用可選引數定義函式。要做到這一點,需要在可選引數的名稱前加上符號 &optional

讓我們編寫一個函式,用於顯示接收到的引數。

示例

建立一個名為 main.lisp 的新原始碼檔案,並輸入以下程式碼。

main.lisp

; define a function with optional parameters
(defun show-members (a b &optional c d) (write (list a b c d)))
; call the method with an optional parameter
(show-members 1 2 3)
; terminate printing
(terpri)
; call method with all optional parameter
(show-members 'a 'b 'c 'd)
; terminate printing
(terpri)
; call method with no optional paramter
(show-members 'a 'b)
; call method with all optional parameter
(terpri)
(show-members 1 2 3 4)

輸出

執行此程式碼後,它返回以下結果:

(1 2 3 NIL)
(A B C D)
(A B NIL NIL)
(1 2 3 4)

請注意,在上述示例中,引數 c 和 d 是可選引數。

示例 - 多個數字的和

更新名為 main.lisp 的檔案,並輸入以下程式碼。在此程式碼中,我們會獲取傳遞的數字的和。

main.lisp

; define a function with optional parameter
(defun sum (a b &optional c) 
   ; check if c is not defined
   (if(not c)
      ; get sum of two numbers   
      (write (+ a b))
	  ; otherwise get sum of all numbers
      (write (+ a b c))
   ))

; terminate printing
(terpri)
; call method with no optional parameter
(sum 1 2)
; terminate printing
(terpri)
; call method with optional parameter
(sum 1 2 3)

輸出

執行此程式碼後,它返回以下結果:

3
6

示例 - 多個數字的乘積

更新名為 main.lisp 的檔案,並輸入以下程式碼。在此程式碼中,我們會獲取傳遞的數字的和。

main.lisp

; define a function with optional parameter
(defun product (a b &optional c) 
   ; check if c is not defined
   (if(not c)
      ; get product of two numbers 
      (write (* a b))
      ; otherwise get product of all numbers
      (write (* a b c))
   ))
; terminate printing
(terpri)
; call method with no optional parameter
(product 1 2)
; terminate printing
(terpri)
; call method with optional parameter
(product 1 2 3)

輸出

執行此程式碼後,它返回以下結果:

2
6
lisp_functions.htm
廣告