Lisp - 函式返回的值



預設情況下,LISP 中的函式以作為返回值計算的最後一個表示式的值作為返回值。以下示例演示了這一點。

示例

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

main.lisp

; define a function add-all which will return sum of passed numbers
(defun add-all(a b c d)
   (+ a b c d)
)
; set sum as result of add-all function
(setq sum (add-all 10 20 30 40))
; print value of sum
(write sum)
; terminate printing
(terpri)
; print value of result of add-all function
(write (add-all 23.4 56.7 34.9 10.0))

輸出

執行程式碼後,它將返回以下結果 -

100
125.0

但是,你可以使用 return-from 特殊運算子,以立即從函式返回任何值。

示例

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

main.lisp

; define a function to return a number as 10
(defun myfunc (num)
   (return-from myfunc 10)
   num
)
; print result of function call
(write (myfunc 20))

輸出

執行程式碼後,它將返回以下結果 -

10

稍作更改的程式碼 -

main.lisp

; define a function to return a number as 10
(defun myfunc (num)
   (return-from myfunc 10)
   write num
)
; print result of function call
(write (myfunc 20))

輸出

它仍然返回 -

10
lisp_functions.htm
廣告
© . All rights reserved.