Lisp - 引數剩餘



某些函式需要接受可變數量的引數。

例如,我們正在使用的 **format** 函式需要兩個必填引數,即流和控制字串。但是,在字串之後,它需要可變數量的引數,具體取決於要在字串中顯示的值的數量。

類似地,+ 函式或 * 函式也可能接受可變數量的引數。

可以使用符號 **&rest** 來提供對這種可變數量的引數的支援。

以下示例說明了這個概念:

示例

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

更新 main.lisp 檔案,並在其中鍵入以下程式碼。

main.lisp

; define a function to print arguments
(defun show-members (a b &rest values) (write (list a b values)))
; call the show-members function with three parameters
(show-members 1 2 3)
; terminate printing
(terpri)
; call the show-members function with four parameters
(show-members 1 2 3 4)
; terminate printing
(terpri)
; call the show-members function with nine parameters
(show-members 1 2 3 4 5 6 7 8 9)

輸出

執行程式碼時,將返回以下結果:

(1 2 (3))
(1 2 (3 4))
(1 2 (3 4 5 6 7 8 9))

示例

更新名為 main.lisp 的原始碼檔案,並在其中鍵入以下程式碼。

更新 main.lisp 檔案,並在其中鍵入以下程式碼。

main.lisp

; define a function to print arguments
(defun show-members (a b &rest values) (write (list a b values)))
; call the show-members function with four parameters
(show-members 'a 'b 'c 'd)
; terminate printing
(terpri)
; call the show-members function with two parameters
(show-members 'a 'b)

執行程式碼時,將返回以下結果:

(A B (C D))
(A B NIL)

示例

更新名為 main.lisp 的原始碼檔案,並在其中鍵入以下程式碼。

更新 main.lisp 檔案,並在其中鍵入以下程式碼。

main.lisp

; define a function to print arguments
(defun show-members (a b &rest values) (write (list a b values)))
; call the show-members function with three parameters
(show-members 1.0 2.0 3.0)
; terminate printing
(terpri)
; call the show-members function with four parameters
(show-members 1.0 2.0 3.0 4.0)
; terminate printing
(terpri)
; call the show-members function with nine parameters
(show-members 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0)

執行程式碼時,將返回以下結果:

(1.0 2.0 (3.0))
(1.0 2.0 (3.0 4.0))
(1.0 2.0 (3.0 4.0 5.0 6.0 7.0 8.0 9.0))
lisp_functions.htm
廣告