
- LISP 教程
- LISP - 主頁
- LISP - 概述
- LISP - 環境
- LISP - 程式結構
- LISP - 基本語法
- LISP - 資料型別
- LISP - 宏
- LISP - 變數
- LISP - 常量
- LISP - 運算子
- LISP - 判定
- LISP - 迴圈
- LISP - 函式
- LISP - 謂詞
- LISP - 數值
- LISP - 字元
- LISP - 陣列
- LISP - 字串
- LISP - 序列
- LISP - 列表
- LISP - 符號
- LISP - 向量
- LISP - 集合
- LISP - 樹
- LISP - 雜湊表
- LISP - 輸入和輸出
- LISP - 檔案輸入/輸出
- LISP - 結構
- LISP - 程式包
- LISP - 錯誤處理
- LISP - CLOS
- 有關 Lisp 的有用資源
- Lisp - 快速指南
- Lisp - 有用資源
- Lisp - 討論
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
廣告