Lisp - 關鍵字引數



關鍵字引數允許你指定哪些值與哪些特定引數匹配。

它使用 &key 符號表示。

當你將值傳送到函式時,你必須用 :parameter-name. 為值加上字首。

以下示例說明了此概念。

示例

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

main.lisp

; define a function show-members to print list of arguments passed
(defun show-members (&key a b c d ) (write (list a b c d)))
; call function with three parameters
(show-members :a 1 :c 2 :d 3)
; terminate printing
(terpri)
; call function with two parameters
(show-members :a 1 :b 2)

輸出

當你執行該程式碼時,它將返回以下結果 −

(1 NIL 2 3)
(1 2 NIL NIL)

示例

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

main.lisp

; define a function show-members to print list of arguments passed
(defun show-members (&key a b c d ) (write (list a b c d)))
; call function with three parameters
(show-members :a 'p :b 'q :c 'r :d 's)
; terminate printing
(terpri)
; call function with two parameters
(show-members :a 'p :d 'q)

輸出

當你執行該程式碼時,它將返回以下結果 −

(P Q R S)
(P NIL NIL Q)

示例

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

main.lisp

; define a function show-members to print list of arguments passed
(defun show-members (&key a b c d ) (write (list a b c d)))
; call function with three parameters
(show-members :a 1.0 :c 2.0 :d 3.0)
; terminate printing
(terpri)
; call function with two parameters
(show-members :a 1.0 :b 2.0)

輸出

當你執行該程式碼時,它將返回以下結果 −

(1.0 NIL 2.0 3.0)
(1.0 2.0 NIL NIL)
廣告
© . All rights reserved.